简体   繁体   中英

Remove Dynamically Added Fields with Javascript

I have a form where I am cloning the initial input fields as a template to allow the user to add as many options as they need to. Adding new fields works fine, but when attempting to remove them, the first one works as expected but all generated fields cannot be removed.

My knowledge of JS is very poor but I would assume that setting it to remove the parent should be the correct operation.

<script type="text/javascript">
$(function()
{
    var template = $('#inventoryItems .inventory:first').clone(),
        inventoryCount = 1;

    var addInventory = function()
    {
        inventoryCount++;
        var inventory = template.clone().find(':input').each(function()
        {
            var newId = this.id.substring(0, this.id.length-1) + inventoryCount;
            $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
            this.name = this.id = newId; // update id and name (assume the same)
        }).end() // back to .attendee
        .attr('id', 'inv' + inventoryCount) // update attendee id
        .appendTo('#inventoryItems > fieldset'); // add to fieldset
    };

    $('.btnAddInventory').click(addInventory); // attach event
});

$(function()
{
    var removeInventory = function()
    {
        $(this).parent().remove();
    };

    $('.btnRemoveInventory').click(removeInventory); // attach event
});
</script>

HTML:

                <div id="inventoryItems" class="inventoryItems" style="margin:0; padding:0;">

                    <fieldset style="width:62%; float:left; margin-left: 19%;">

                        <label>Inventory</label>
                        <div id="inv1" class="inventory">
                            <select name="invItem1" style="width:92%;">
                                <?php
                                    $invItem_values = array("id", "name");
                                    display_options_list($dp_conn, $invItem_values, "inventory", "id");
                                ?>
                            </select>

                            <input class="btnRemoveInventory" type="button" style="background: url(images/icn_trash.png) no-repeat; cursor:pointer; border: none;">
                        </div>

                    </fieldset><div class="clear"></div>

                    <!-- Add Inventory Button -->
                    <div style="width:62%; margin:0; padding:0; float: right; margin-right: 19%">
                        <input class="btnAddInventory" type="button" value="Add Item" style="float: right;">
                    </div><div class="clear"></div>

                </div>

Attaching events via click() (or any other shortcut event handler) only works with elements which are available on load of the page. Instead, because you are appending elements dynamically, you need to use a delegated event handler. Change this:

$('.btnRemoveInventory').click(removeInventory)

To this:

$('#inventoryItems').on('click', '.btnRemoveInventory', removeInventory)

This is attaching the event to the nearest static element, #inventoryItems , and then filters the events raised to see if the target matches .btnRemoveInventory .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM