JQuery 1.10.1 cannot remove parents <p>

163 Views Asked by At

I have a slightly modified JSFiddle to support my production JQuery version (1.10.1, original version uses 1.4.3). I could not get 'Remove' link to remove newly created <p> after I click on 'Add new input box'. I think the problem is located in

$(this).parents('p').remove();

Modified version: http://jsfiddle.net/x68jx/

Original version: http://jsfiddle.net/jaredwilli/tZPg4/4/

2

There are 2 best solutions below

1
On BEST ANSWER

For dynamic added element, you have to use event delegation. And id should be unique, so use class instead.

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').click(function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        scntDiv.on('click', '.remScnt', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

The WORKING DEMO.

0
On

Use event delegation since the label is dynamically added:

scntDiv.on("click", ".remScnt", function() { 
    if( i > 2 ) {
        $(this).parents('p').remove();
        i--;
    }
    return false;
});

Also, as mentioned by @xdazz you should avoid duplicating ID's at all costs. Use a class instead.

http://jsfiddle.net/x68jx/4/