0

I'm trying to create a list application that will let a user inputs an item into a text field that will be dynamically created on submit (list tag). I then want to be able to delete any of the item added individually (using a delete button that will be added next to each list tag).

So far I managed to create the Array of Objects after submitting input field.

How can I only grab the "value" of Array Object in order to create my list tag dynamically? How can I then delete the element selected?

I would like to complete that application by using the Observer Pattern.

See my code bellow: http://jsfiddle.net/Lk3p8/

Thanks

John
  • 3,529
  • 14
  • 42
  • 48

1 Answers1

0

I've created an updated version of your jsFiddle that seems to do what you want.

..edit... updated to reflect your request. I didnt notice that you were saving it in the values array. Sorry about that. I've also made some slight changes to your markup.

$(document).ready(function(){

var deleteBtn = "<input class='deleteitem' type='button' value='Delete' name='delete' id='delete' />";
var values = [];
$("#myForm").submit(function(){
    var frm= $("#myForm").serializeObject();

    values.push(frm.item);


    $("#display").append("<li><p>" + frm.item +"</p>"+  deleteBtn +"</li>");
    return false;
});


$("#display").on("click", ".deleteitem", function(event){
    var removeItem = $(this).parent().children('p').text();
     $('.log').after("<p>"+removeItem +  " removed</p>");      
    $(this).parent().remove();


    values = jQuery.grep(values, function(value) {
       return value != removeItem;
    });

    console.log(values);
});


});

The proof of concept markup isnt the greatest, but you get the idea.

Jason Kulatunga
  • 5,814
  • 1
  • 26
  • 50
  • Thanks for your quick response and for updating jSFiddle. Regarding the delete button I wanted to amend the Array of Objects accordingly (to reflect the list of element). For instance when deleting an item (DOM element) the appropriate object would also be removed from the Array "values". – John May 30 '12 at 22:45
  • Thanks, I get the idea. One more question - any tips or documentation on how to write this application using the observer pattern (trying to learn it)? – John May 30 '12 at 23:13
  • I personally use Peter Higgins's pubsub implementation of the observer pattern https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js the only change I made is adding a try catch block around the publish method. I also found this [js design pattern guide](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript) useful for learning about different design patterns and when to use them. – Jason Kulatunga May 30 '12 at 23:20