Keep form fields in sequence when adding dynamic inputs with jquery/javascript

I am using the below code to to add / remove rows of inputs. If a row is deleted, I want the input names to stay in sequence, not skip a number that was deleted. Right now if a row is deleted, that number is skipped.

Can someone assist? Thank you.

<form method="post" action="actionpage.cfm">
<input type="hidden" name="totalfields" />
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="name1"> <input type="radio" name="auth1" value="auth">Authorized <input type="radio" name="auth1" value="noauth">Not Authorized </div>
</div>
<input type="submit" value="submit">
</form>

<script type="text/javascript">
$(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();
        var total = $('.input_fields_wrap div').length;
        if(total < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="name' + x + '"/> <input type="radio" name="auth' + x + '" value="auth">Authorized <input type="radio" name="auth' + x + '" value="noauth">Not Authorized <a href="#" class="remove_field">Remove</a></div>'); //add input box
      $('input[name="totalfields"]').val(total+1);
        }
    });
   
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); 
        $(this).parent('div').remove(); 
		
		// GET THE TOTAL INPUTS USING JQUERY
        var total = $('.input_fields_wrap div').length;
		
		// SET THE TOTAL NUMBER OF INPUTS
        $('input[name="totalfields"]').val(total);
    })
});
</script>

Open in new window

earwig75Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Try this code
var max_fields      = 10; //maximum input boxes allowed

$(function() {
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    $(add_button).click(function(e){ //on add input button click
    e.preventDefault();

    // Get the number of divs in the pile
    var length = $('.input_fields_wrap > div').length;

    // Check that we have not reached the max
    if (length < max_fields) {
  
      // Create the new div
      var div = $('<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 Field<a/></div>');
      // Increment length because we are dealing with the next 1
      length++;
    
    // Set the name value for the new div using the length 
    // last man in so the length is the one to use
      $('input', div).each(function() {
	    var name = $(this).attr('name');
        $(this).attr('name', name + length);
      });
    
    // Add it
      wrapper.append(div);
    
    // Update hidden val
      $('input[name="totalfields"]').val(length);
    }
  });


    //user click on remove text
  wrapper.on("click",".remove_field", function(e){ 
    e.preventDefault(); 
  
    //  Remove the closest div
    $(this).closest('div').remove();

    // Get list of active divs
    var divs = $('.input_fields_wrap > div');
    // Loop through them
    divs.each(function(i) {

      // Loop through the inputs in each one
      $('input', $(this)).each(function() {
        // Get the name value
        var name = $(this).attr('name');
    
        // Do a regex replace of the digit
        // WARNING: names cannot contain other numbers
        name = name.replace(/\d+/, i+1);
    
        // Put it back
        $(this).attr('name', name);
      });
    });
    // Update hidden value
    $('input[name="totalfields"]').val(divs.length);
  })
});

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
earwig75Author Commented:
Unfortunately this doesn't work.

The first line is above the function so I moved it into the function. When I click "add more fields", instead of adding a new row it submits the form.

I also updated the code in this new question to use radio buttons, but the script you recommend is still using check boxes.

Thanks.
0
earwig75Author Commented:
Ok, it's working. I just had to update the first 2 lines like the below, and change the check boxes to radio buttons. Thanks again for all of your help.

$(document).ready(function() {
      var max_fields      = 10; //maximum input boxes allowed
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Julian HansenCommented:
Here is a working sample
http://www.marcorpsa.com/ee/t955.html
0
Julian HansenCommented:
Just for interest
$(document).ready(function() {

Open in new window

Can be shortened to
$(function() {

Open in new window

0
Julian HansenCommented:
This does not need to be outside the $(function() - it is global and will be accessible anywhere on the page from its point of declaration onwards - refer to the sample for a working example.
 var max_fields      = 10; //maximum input boxes allowed 

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.