jQuery append and remove dynamic table row

user770668 picture user770668 · Apr 24, 2013 · Viewed 256.1k times · Source

I can add many rows for a table, but I can't remove many rows. I only can remove 1 row per sequential add.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
        $("#remCF").on('click',function(){
            $(this).parent().parent().remove();
        });
    });
});
</script>

<table class="form-table" id="customFields">
<tr valign="top">
    <th scope="row"><label for="customFieldName">Custom Field</label></th>
    <td>
        <input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp;
        <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp;
        <a href="javascript:void(0);" id="addCF">Add</a>
    </td>
</tr>
</table>

You can see the code at http://jsfiddle.net/3AJcj/

I need help.

Answer

Samuel Liew picture Samuel Liew · Apr 24, 2013

You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.

Also, move the .on() outside of the .click() function, as you only need to set it once.

http://jsfiddle.net/samliew/3AJcj/2/

$(document).ready(function(){
    $(".addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});