Search code examples
jqueryhtmladditionform-fields

Remove last input field in dynamic list with jQuery


How I can manage to remove the last <div><input type="text" name="mytext[]"></div> even from the "top" button for remove? When I create many fields, when I click the "remove glyphicon on top of them" it deletes all, not the last.

When I click the button for remove on the right of the field when I make new field it removes the field, but I want to remove also and from the top buttons

<div class="input_fields_wrap">
    <button class="add_field_button">
        <span class="glyphicon glyphicon-plus"></span>
    </button>
    <button class="remove_field" ><span class="glyphicon glyphicon-trash"></span>
    </button>
    <div><input type="text" name="mytext[]"></div>
</div>
$(document).ready(function () {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID
    var x = 1; //initlal text box count
    $(add_button).click(function (e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">\n\
                                <button ><span class="glyphicon glyphicon-trash"></button>\n\
                                </span></a></div>'); //add input box
        }
    });
    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});

Solution

  • To solve this you can use nextAll('div:last'). Try this:

    $wrapper.on("click", ".remove_field", function(e) { //user click on remove glyphicon
        e.preventDefault();
        $(this).nextAll('div:last').remove();
        x--;
    })
    

    Working example

    Note that I amended the JS slightly so that you're not double-wrapping your jQuery objects, and I also amended the HTML slightly so that it was obvious which was the add/remove buttons even without using glyphicons.