简体   繁体   中英

Delete dynamically generated fields

I am able to generate the dynamic fields but when i am trying to delete the fields rather then deleting the elements in front of the delete button it is deleting from last towards first

    <script>
    $(document).ready(function(){
        var max_fields = 10;
        var wrapper = $(".more");
        var add_button = $(".add");
        var x = 1;
        $(add_button).click(function(e){
            e.preventDefault();
            if (x < max_fields){
                x++;
                $(wrapper).append('<div id="box'+x+'" class="row"><div class="col-sm-3 mb-3"><select name="feeType[]" class="form-control shadow-sm" required><option value="" selected disabled>Select Fee</option><option value="Admission">Admission Fee</option><option value="Development">Development Fee</option><option value="Annual">Annual Fee</option><option value="Tuition">Tuition Fee</option></select></div><div class="col-sm-3 mb-3"><input type="number" name="amount[]" class="form-control shadow-sm" placeholder="Amount" required></div><div class="col-sm-3 mb-3"><button class="delete btn btn-danger shadow-sm">Delete Fields</button></div></div>'); //add input box
            }else{
                alert('You Reached the limits')
            }
        });
        $(wrapper).on("click", ".delete", function(e){
            e.preventDefault();
            $('#box'+x).remove();
            x--;
        })
    });
    </script>

Because x 's value will always be just the number of element that were dynamically created.

A possible solution would be to find the 'remove' button that was clicked and remove it's parent. replace $('#box'+x).remove(); with this $(this).parents('.row').remove();

A working fiddle example: https://jsfiddle.net/3L986nbj/

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