Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery remove append input

Tags:

jquery

    $(document).ready(function() {
        var n=1;

        $("#add").click(function(){
            if(n<8){
            $("#form").append("
                <input type='text' name='input_" + (n++) +"'/>
                <input type='button' id='remove_" + (n++) +"' value='REMOVE'/>");
            }
        });     
    });

I have a Jquery add input text.

How can I remove the specific input.

http://jsfiddle.net/JvW3L/

like image 787
user2178521 Avatar asked Aug 04 '26 12:08

user2178521


1 Answers

Assuming an element with the id of 'deleteInput' is to be clicked to trigger the deletion:

$('#deleteInput').click(function(e){
    // in case it's an element with a default action:
    e.preventDefault();
    $('#form input').last().remove();
    n--;
});

The above will simply remove the last input element added, and decrement the n variable.

If, on the other hand, you want to remove a specific input, other than the last:

$('.deleteInput').click(function(e){
    e.preventDefault();
    $(this).prev('input').remove();
});

This assumes that the element, with a class of deleteInput will immediately follow the input to be removed. In this case I'm leaving n as-is, and leaving you to find some way of re-using the vacated/emptied 'slot' for the input to be recreated (since a simple decrement would probably cause two elements to (invalidly) share the same id.

References:

  • click().
  • event.preventDefault().
  • last().
  • prev().
  • remove().
like image 149
David Thomas Avatar answered Aug 06 '26 03:08

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!