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
- <script>
- $(document).ready(function() {
- var max_fields_limit = 10; //set limit for maximum input fields
- var x = 1; //initialize counter for text box
- $('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
- e.preventDefault();
- if(x < max_fields_limit){ //check conditions
- x++; //counter increment
- $('.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
- }
- });
- $('.input_fields_container').on("click",".remove_field", function(e){ //user click on remove text links
- e.preventDefault(); $(this).parent('div').remove(); x--;
- })
- });
- </script>
Here i add simple input field with add more button.
- <div class="input_fields_container">
- <div><input type="text" name="product_name[]">
- <button class="btn btn-sm btn-primary add_more_button">Add More Fields</button>
- </div>
- </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.
- <?php
- print '<pre>';
- print_r($_REQUEST['product_name']);
- print '</pre>';
- //output of above script
- Array
- (
- [0] => value of 1st index
- [1] => value of 2nd index
- [2] => value of 3rd index
- )
- ?>