Link to home
Start Free TrialLog in
Avatar of earwig75
earwig75

asked on

Append number to input fields with jquery/javascript dynamically

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

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of earwig75
earwig75

ASKER

Perfect, thank you.
You are welcome.