Add Remove input fields dynamically using jQuery

Add Remove input fields dynamically using jQuery

In this tutorial, I am going to tell you how to add dynamic fields in a form.

Here i write a script to add multiple input fields with remove button.

By clicking on remove links, related input field will be removed from list of fields easily.

By using jQuery for such type of activity it become much more easier.

You will know how to get value of this field in your PHP script after form submission.

In this script i set the limit on adding input field, you can add maximum 10 input fields but you can change as per your needs.

By default i start from single input field after that you can add more input fields by clicking on add more fileds button.

You need to include jquery library before going to use this script.

Script for add remove input fields dynamically

  1. <script>
  2.     $(document).ready(function() {
  3. var max_fields_limit = 10; //set limit for maximum input fields
  4. var x = 1; //initialize counter for text box
  5. $('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
  6. e.preventDefault();
  7. if(x < max_fields_limit){ //check conditions
  8. x++; //counter increment
  9. $('.input_fields_container').append('<div><input type="text" name="product_name[]"/><a href="#" class="remove_field" style="margin-left:10px;">Remove</a></div>'); //add input field
  10. }
  11. });
  12. $('.input_fields_container').on("click",".remove_field", function(e){ //user click on remove text links
  13. e.preventDefault(); $(this).parent('div').remove(); x--;
  14. })
  15. });
  16. </script>

Here i add simple input field with add more button.

  1. <div class="input_fields_container">
  2.     <div><input type="text" name="product_name[]">
  3.          <button class="btn btn-sm btn-primary add_more_button">Add More Fields</button>
  4.     </div>
  5. </div>

You can get value of this fields in your PHP script by field name as you access normally but it return as an array after submitting form.

  1. <?php
  2. print '<pre>';
  3. print_r($_REQUEST['product_name']);
  4. print '</pre>';
  5. //output of above script
  6. Array
  7. (
  8. [0] => value of 1st index
  9. [1] => value of 2nd index
  10. [2] => value of 3rd index
  11. )
  12. ?>

Phone: (+91) 8800417876
Noida, 201301