add remove input fields dynamically using jquery
In this article, you can read more about how to add remove input fields dynamically using jquery. if you want to add or remove input fields dynamically then you can see the following example.
sometimes we need to add bulk data. eg. education data. so here we are taking one input box and explaining you through a simple example.
max_fields: The maxField variable is the maximum number of input fields that will be added.
wrapper: The wrapper variable selects the parent element of the input fields.
add_button: The addButton variable will select the add button element.
remove_field: The user click on remove button then will be removed input field.
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <?php if(isset($_POST['btnSubmit'])){ $name = $_POST['name']; echo "<pre>"; print_r($name); echo "</pre>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>add remove input fields dynamically using jquery - XpertPhp<title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script> $(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" placeholder="Enter Name" name="name[]"/> <a href="#" class="remove_field btn btn-danger btn-sm">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--; }) }); </script> </head> <body> <div class="container"> <form class="form-inline" method="post"> <div class="input_fields_wrap"> <div><input type="text" placeholder="Enter Name" name="name[]"> <button class="add_field_button btn btn-primary btn-sm">Add More Fields</button></div> </div> <button type="submit" name="btnSubmit" class="btn btn-default">Submit</button> </form> </div> </body> </html> |
Read Also
Laravel 7 Livewire Add Or Remove Dynamically Input Fields
Please follow and like us: