Javascript 添加/删除所有文本框id增量

Javascript 添加/删除所有文本框id增量,javascript,jquery,Javascript,Jquery,如何在所有文本框中设置添加/删除id自动递增(ItemCode、ItemName添加到+1,删除到-1。) Sr 项目代码 项目名称 $(文档).ready(函数(){ $(“.add”)。单击(函数(){ 变量长度=$('.one').length; var cloned=$(this).clonest('.one').clone(true); 克隆的.appendTo(“#mainDiv”).find('.sno').val(长度+1); cloned.find(':input:not(

如何在所有文本框中设置添加/删除id自动递增(ItemCode、ItemName添加到+1,删除到-1。)


Sr
项目代码
项目名称
$(文档).ready(函数(){
$(“.add”)。单击(函数(){
变量长度=$('.one').length;
var cloned=$(this).clonest('.one').clone(true);
克隆的.appendTo(“#mainDiv”).find('.sno').val(长度+1);
cloned.find(':input:not(“.sno”).val(“”);
var parent=$(this).closest('.one');
});
$('.delete')。单击(函数(){
如果($('.one')。长度==1){
警报(“这是默认行,不能删除”);
返回false;
}
var parent=$(this).closest('.one');
$(this.parents(“.one”).remove();
//重新设置序列号
$('.sno')。每个(函数(i){
该值=i+1;
})
});
});

这里的示例

尝试将此代码添加到添加事件中

cloned.find('input[name="ItemCode[]"]').attr('id','ItemCode'+(length + 1));
cloned.find('input[name="ItemName[]"]').attr('id','ItemName'+(length + 1));

您可以使用以下功能重置序列号。检查JSFIDLE


这是你能做的。这也将在删除时重置id

由于标签的
for
属性应绑定到输入
id
,因此您可能还需要更改这些属性

$(文档).ready(函数(){
$(“.add”)。单击(函数(){
变量长度=$('.one').length;
var cloned=$(this).clonest('.one').clone(true);
克隆的.appendTo(“#mainDiv”).find('.sno').val(长度+1);
cloned.find(':input:not(“.sno”).val(“”);
cloned.find(“label[for*='ItemCode']”).attr('for','ItemCode'+(长度+1));
cloned.find(“输入[id*='ItemCode']”).attr('id','ItemCode'+(长度+1));
cloned.find(“label[for*='ItemName']”).attr('for','ItemName'+(长度+1));
cloned.find(“输入[id*='ItemName']”).attr('id','ItemName'+(长度+1));
var parent=$(this).closest('.one');
});
$('.delete')。单击(函数(){
如果($('.one')。长度==1){
警报(“这是默认行,不能删除”);
返回false;
}
var parent=$(this).closest('.one');
$(this.parents(“.one”).remove();
$('.one')。每个(函数(索引,项){
$(this.find('.sno').val(索引+1);
$(this.find(“label[for*='ItemCode']”)attr('for','ItemCode'+(index+1));
$(this.find(“input[id*='ItemCode']”)。attr('id','ItemCode'+(index+1));
$(this).find(“label[for*='ItemName']”).attr('for','ItemName'+(index+1));
$(this.find(“输入[id*='ItemName']”)。attr('id','ItemName'+(索引+1));
});
});
});

Sr
项目代码
项目名称

你能提供更多关于你所拥有的以及你想要实现的目标的详细信息吗?@Nilesh检查修改后的解决方案first work(第一次添加)按钮。Ayoub Oulaika和DavidDomain先生在这里举了一个例子,在ItemName(id)not+1@Nilesh中调用ajax-对不起,我不明白你的意思。您使用的代码与您在这篇文章中的问题相同。DavidDomain这是个问题解决谢谢你的帮助
cloned.find('input[name="ItemCode[]"]').attr('id','ItemCode'+(length + 1));
cloned.find('input[name="ItemName[]"]').attr('id','ItemName'+(length + 1));
function ResetSerialNumbers(){
  $('.sno').each(function(i){
  var val = i+1;
  this.value=val;
  $(this).closest('.row').find("input[id^='ItemCode']").first().attr("id",'ItemCode'+val);
    $(this).closest('.row').find("input[id^='ItemName']").first().attr("id",'ItemName'+val);
});
}