Javascript Jquery如何使用动态添加的字段为name属性添加计数器

Javascript Jquery如何使用动态添加的字段为name属性添加计数器,javascript,jquery,forms,validation,Javascript,Jquery,Forms,Validation,您好,我有一个包含这两个字段的表单,用户可以在其中动态添加其他字段 <section class="multi-field-wrapper"> <h2>Ingredients</h2> <div class="multi-fields"> <div class="f-row ingredient"> <input type="text" name="ingredient

您好,我有一个包含这两个字段的表单,用户可以在其中动态添加其他字段

 <section class="multi-field-wrapper">                          
 <h2>Ingredients</h2>
 <div class="multi-fields">
 <div class="f-row ingredient">
 <input type="text" name="ingredients[]"placeholder="Ingredients *"/>
 <input type="text"  name="quantity[]" placeholder="Quantity" />
 <button type="button" class="remove">-</button>
 </div>
 </div>
 <div class="f-row full">
 <button type="button" class="add">Add an ingredient</button>
 </div>
 </section>

<script>
$('.multi-field-wrapper').each(function() {
    var $wrapper = $('.multi-fields', this);
    $(".add", $(this)).click(function(e) {
        $('.f-row.ingredient:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
   });
    $('.f-row.ingredient .remove', $wrapper).click(function() {

        if ($('.f-row.ingredient', $wrapper).length > 1)
            $(this).parent('.f-row.ingredient').remove();
    });
});
</script>


<script>
$('.multi-field-wrapper').each(function() {
    var $wrapper = $('.multi-fields', this);
    $(".add", $(this)).click(function(e) {
        $('.f-row.instruction:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('')
    });
    $('.f-row.instruction .remove', $wrapper).click(function() {

        if ($('.f-row.instruction', $wrapper).length > 1)
            $(this).parent('.f-row.instruction').remove();
    });
});
</script>

成分
-
添加配料
$('.multi-field wrapper')。每个(函数(){
var$wrapper=$('.multi-fields',this);
$(“.add”,$(this))。单击(函数(e){
$('.f-row.component:first child',$wrapper).clone(true).appendTo($wrapper.find('input').val('').focus();
});
$('.f-row.component.remove',$wrapper)。单击(函数(){
如果($('.f-row.component',$wrapper).length>1)
$(this).parent('.f-row.component').remove();
});
});
$('.multi-field wrapper')。每个(函数(){
var$wrapper=$('.multi-fields',this);
$(“.add”,$(this))。单击(函数(e){
$('.f-row.instruction:first child',$wrapper).clone(true).appendTo($wrapper.find('input').val('')
});
$('.f-row.instruction.remove',$wrapper)。单击(函数(){
if($('.f-row.instruction',$wrapper).length>1)
$(this).parent('.f-row.instruction').remove();
});
});
我正在使用**Jquery验证插件,我已经阅读了所有的线程,我知道我不能对多个输入字段使用相同的名称。我需要的是一种方法,为上面的Jquery脚本添加名称属性的计数器或索引,而不是另一个附加结果的脚本,以便获得一些结果像这样:

字段1:成分[0] 字段2:成分[1] ……等等

验证后如何删除括号之间的索引


谢谢大家!

我没有收到你的问题。上面的代码将只验证第一个输入字段。为了让Jquery验证插件工作并验证所有动态添加的字段。我需要为每个输入指定一个唯一的名称,因此我需要为name属性添加一个计数器以使其唯一。您可以像以前那样命名变量,或像IngCredits1、IngCredits2之类的东西。。。对于验证,您可以在提交时将所有元素值加入数组/列表,并发送到服务器,您的服务器方法可以在其中接受列表。您能告诉我如何执行此操作吗?