Jquery Clone method increment name tag

Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.

Here is my fiddle

https://jsfiddle.net/o5wam5r2/

and here is my JS code

 var formItem;
 $(document).ready(function() {
    //Clone and remove your div instead of hiding it
    formItem = $('.ScheduleextraPartTemplate').clone();
  $('.ScheduleextraPartTemplate').remove();
  formItem.addClass('clone clone-1');
  $('#Schedulecontainer').append(formItem);
 });

 $(document).on('click', '#ScheduleaddRow', function() {
    var cloneForm = $('.clone').last().clone();
  var cloneNum = $('.clone').length;
  cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
  var date = cloneForm.find('[name="txtSchedule"]').val();
  cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
  $('#Schedulecontainer').append(cloneForm);
 })

function addOneMonth(date) {
    var year = parseInt(date.split("-")[0]);
    var month = parseInt(date.split("-")[1]) + 1;
    var day = parseInt(date.split("-")[2]);
    if(month > 12) {
        month = month - 12;
      year++
    }
    return year + "-" + month + "-" + day;
}

Answers 1

  • I fixed it by changing a little piece of code

     var formItem;
     var counter = 0;
     $(document).ready(function() {
        //Clone and remove your div instead of hiding it
    formItem = $('.ScheduleextraPartTemplate').clone();
      formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
      formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
    $('.ScheduleextraPartTemplate').remove();
      formItem.addClass('clone clone-1');
    
    $('#Schedulecontainer').append(formItem);
    });
    
     $(document).on('click', '#ScheduleaddRow', function() {
        var lens = counter++;
        var cloneForm = $('.clone').last().clone();
      var cloneNum = $('.clone').length;
      cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
      var date = cloneForm.find('[name^="txtSchedule"]').val();
      cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
      cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
      cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
    
    $('#Schedulecontainer').append(cloneForm);
    })
    
    function addOneMonth(date) {
    var d = new Date( date );
    d.setMonth( d.getMonth( ) + 1 );
    return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
    }
    

Related Articles