In this blog post, the following example demonstrates how to add/remove multiple input fields dynamically or we can say how to add/remove textbox dynamically with jQuery in a very simple way. It is very useful when you want to receive multiple inputs for the same field in an HTML form.
- Keep reading on Simple jQuery Form Validation Example, Custom Paging in MVC using jQuery
How to add/remove textbox dynamically with jQuery
We will need to add the jQuery library, include the jQuery library before the following jQuery script. Find the full source code below:-
HTML
<!DOCTYPE html> <html lang="en-US"> <head> <title>add/remove multiple input fields dynamically with jquery</title> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var maxField = 10; //Input fields increment limitation var addButton = $('.add_button'); //Add button selector var wrapper = $('.field_wrapper'); //Input field wrapper var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>'; //New input field html var x = 1; //Initial field counter is 1 //Once add button is clicked $(addButton).click(function(){ //Check maximum number of input fields if(x < maxField){ x++; //Increment field counter $(wrapper).append(fieldHTML); //Add field html } }); //Once remove button is clicked $(wrapper).on('click', '.remove_button', function(e){ e.preventDefault(); $(this).parent('div').remove(); //Remove field html x--; //Decrement field counter }); }); </script> <style type="text/css"> input[type="text"] { height: 20px; vertical-align: top; } .field_wrapper div { margin-bottom: 10px; } .add_button { margin-top: 10px; margin-left: 10px; vertical-align: text-bottom; } .remove_button { margin-top: 10px; margin-left: 10px; vertical-align: text-bottom; } </style> </head> <body> <h2>How to add / remove textbox dynamically with jQuery</h2> <div class="container"> <form action="" method="post"> <div class="field_wrapper"> <div> <input type="text" placeholder="Enter your skills:" name="field_name[]" value="" /> <a href="javascript:void(0);" class="add_button" title="Add field"><img src="add-icon.png" /></a> </div> </div> <input type="submit" name="submit" value="SUBMIT" /> </form> </div> </body> </html>
Conclusion
I hope you liked this article on how to add/remove multiple input fields dynamically with jquery. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply