The dynamic input field feature is very useful to get multiple input data for the same field in HTML form. This dynamic add remove input fields feature can be easily implemented with jQuery code.
In this blog, we have shown you an example to add remove input fields dynamically using jQuery.
You can set the limit that how many multiple input fields users can add. Also showing form submit jquery code and get form fields value.
Steps to Create Add Remove Dynamic Input Fields
Step 1: Create an HTML form with the input field.
1 2 3 4 5 6 7 8 9 10 11 |
<form id="contactFrm" action="" method="post"> <div class="section_wrap"> <div> <input type="text" name="InputFieldName[]" value=""/> <a href="javascript:void(0);" class="add_button" title="Add field"> <img src="plus-icon.png"/> </a> </div> </div> <input type="submit" name="submit" value="SUBMIT"> </form> |
Step 2: Add jQuery code to add and remove input fields
Now, add the below jquery code to handle add remove multiple input fields feature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<script type="text/javascript"> $(document).ready(function(){ var MaxFieldsAdd = 5; // set number of fields can user add var addFieldBtn = $('.add_button'); // add field button selecter var submitBtn = $('.section_wrap'); // Input field submitBtn var fieldHTML = '<div><input type="text" name="InputFieldName[]" value=""/><a href="javascript:void(0);" class="deleteBtn"><img src="delete-icon.png"/></a></div>'; var i = 1; //add button action $(addFieldBtn).click(function(){ if(i < MaxFieldsAdd){ i++; $(submitBtn).append(fieldHTML); //append submit button }else { alert('Only '+ MaxFieldsAdd +' field are allowed to add'); } }); //delete button action $(submitBtn).on('click', '.deleteBtn', function(e){ e.preventDefault(); $(this).parent('div').remove(); //Remove field html i--; }); }); </script> |
Get Form Multiple Field Value:
After multiple form fields added and submitted, you can get the field value using $_POST in php file.
1 2 3 4 |
$InputFieldValue = $_POST['InputFieldName']; echo "<pre>"; print_r($InputFieldValue); |
This multiple-input form field output value gets as an array format. You can parse it using foreach loop and use it for further action performed.