Search code examples
javascriptjqueryparents

JQuery 1.10.1 cannot remove parents <p>


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/


Solution

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