Albert Albert - 1 year ago 89
jQuery Question

How to count input name [0] to name [1] when cloned

I am trying to count the index on the input field in a dynamic form that I am using in Laravel, but I can't figure out how to achieve that.

This is my current code I'm using:

HTML:

<div id="language">
<div class="language">
<div class="row">
<div class="form-group col-md-6 col-sm-6">
<input class="form-control" placeholder="Language" name="language[0][name]" type="text">
</div>
<div class="form-group col-md-6 col-sm-6">
<select class="form-control" title="Language level" name="language[0][level]"><option value="medium">Medium</option><option value="good">Good</option><option value="perfect">Perfect</option></select>
</div>
<p><a href="#" class="addsection">Add Section</a></p>
</div>
</div>
</div>


JS:

//Clone fields

//define template
var template = $('#language .language:first').clone();

//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {


//increment
sectionsCount++;

//loop through each input
var section = template.clone().find(':input').each(function(){

//set id to store the updated section number
var newId = this.id + sectionsCount;

//update for label
$(this).prev().attr('for', newId);

//update id
this.id = newId;

}).end()

//inject new section
.appendTo('#language');
return false;


});


When I clone the fields, how can I make [0] count up?
And when I remove the fields that the counts go down?

Answer Source

When you create the new element you need to update the cloned attribute name for the fields so that the value [0] can be [1], [2],....

The code is:

  var txtName = this.getAttribute('name');

  txtName = txtName.replace('[0]', '[' + (sectionsCount - 1) + ']');

  this.setAttribute('name', txtName);

In order to remove a section I added a remove anchor and the code is:

  $('body').on('click', '.removesection', function() {
       $(this).closest('.language').remove();
   });

The snippet:

$(function () {
  //Clone fields

  //define template
  var template = $('#language .language:first').clone();

  //define counter
  var sectionsCount = 1;
  //add new section
  $('body').on('click', '.addsection', function() {


    //increment
    sectionsCount++;

    //loop through each input
    var section = template.clone().find(':input').each(function(){

      //set id to store the updated section number
      var newId = this.id + sectionsCount;

      //update for label
      $(this).prev().attr('for', newId);

      //update id
      this.id = newId;
      var txtName = this.getAttribute('name');
      txtName = txtName.replace('[0]', '[' + (sectionsCount - 1) + ']');
      this.setAttribute('name', txtName);

    }).end()

    //inject new section
    .appendTo('#language');
    return false;


  });

  // remove current section
  $('body').on('click', '.removesection', function() {
    $(this).closest('.language').remove();
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div id="language">
    <div class="language">
        <div class="row">
            <div class="form-group col-md-6 col-sm-6">
                <input class="form-control" placeholder="Language" name="language[0][name]" type="text">
            </div>
            <div class="form-group col-md-6 col-sm-6">
                <select class="form-control" title="Language level" name="language[0][level]"><option value="medium">Medium</option><option value="good">Good</option><option value="perfect">Perfect</option></select>
            </div>
            <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="addsection">Add Section</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="removesection">Remove Section</a></p>
        </div>
    </div>
</div>