Thursday, October 9, 2014

How To Add or Duplicate Input Fields Dynamically Using jQuery?

If you are looking to add and remove duplicate input fields, here's another jQuery example below to do the task for you. This jQuery snippet adds duplicate input fields dynamically and stops when it reaches maximum allowed fields.

If you read comment lines carefully, the process is pretty straight forward. We start with 1 input field and let user add more fields until the count reaches maximum. Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is div element.
$(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
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">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--;

Here's HTML code you need to place within BODY tag of your page, perhaps within a FORM tag.
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
We start with single Input field and a “Add more Field” button to allow user to add more fields. The text input field is wrapped in div element, as explained above, on delete button click, it finds parent element, which is a div and removes it.

How to capture array values using PHP from these input fields and save it in mysql in my next post.

Source: Add/Remove Input Fields Dynamically with jQuery

No comments:

Post a Comment