Jquery Clone方法增量名称标记

时间:2017-02-25 06:20:56

标签: javascript jquery

您好我试图在我的所有表单字段中添加增量从零到数字每当我添加新的克隆时它将下一个数字分配给名称标签,我尝试了所有方法,但没有任何方法适合我。

这是我的小提琴

https://jsfiddle.net/o5wam5r2/

,这是我的JS代码

 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;
}

1 个答案:

答案 0 :(得分:0)

我通过更改一小段代码来修复它

 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);
}