Question Detail

How to add multiple input fields and remove button with help of jquery?

6 years ago Views 2587 Visit Post Reply


Thread Reply

Bili Greed

- 6 years ago

Add/Remove Input Fields Dynamically with jQuery
If you are looking to add and remove duplicate input fields, here’s another jQuery example
Image result for Add/Remove Input Fields jquery
 

HTML

1
2
3
4

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

 

We start with 1 input field and let the user add more fields until the count reaches the maximum. Same process goes to delete button, 

JQUERY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

$(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">Remove</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

 


Try this.