Search code examples
jqueryjsonobserver-patternserializearray

List application using serializeArray and observer pattern


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


Solution

  • 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.