Append number to input fields with jquery/javascript dynamically

earwig75
earwig75 used Ask the Experts™
on
I am using the below to add rows of inputs dynamically to a form. I would like to add an increasing number next to each field name dynamically. So the field names would be: name1 auth1 and then name2 auth2 etc...

Could someone assist?

<form method="post" action="actionPage.cfm">
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="name"> <input type="checkbox" name="auth" value="auth">Authorized <input type="checkbox" name="auth" value="noauth">Not Authorized </div>
</div>
<input type="submit" value="submit">
</form>
<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" name="name"/> <input type="checkbox" name="auth" value="auth">Authorized <input type="checkbox" name="auth" value="noauth">Not Authorized <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--;
    })
});
</script>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Quick and dirty way of doing it - just put your x variable in the appropriate place in the append() string
Like so
$(wrapper).append('<div><input type="text" name="name' + x + '"/> <input type="checkbox" name="auth' + x + '" value="auth">Authorized <input type="checkbox" name="auth' + x  + '" value="noauth">Not Authorized <a href="#" class="remove_field">Remove</a></div>'); //add input box

Open in new window

Author

Commented:
Perfect, thank you.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial