2014-01-15 163 views
3

就在这里是我的HTML ::更改名称

<fieldset> 
    <legend>Attributes</legend> 

    <div class="attr_container"> 
     <div class="attr_entry existent row"> 
      <div class="half"> 
       <label for="attribute[]">Attribute</label> 
       <input id="attribute" maxlength="50" required="required" name="attribute[]" type="text">     
       <p> 
        <a href="javascript:void(0)" class="add_attr"><i class="fa fa-plus-circle"></i> Add Another Attribute</a> 
        <span class="remove">| 
        <a href="javascript:void(0)" class="remove_attr"><i class="fa fa-minus-circle"></i> Remove</a></span> 
       </p> 
      </div> 
      <div class="half"> 
       <label for="designator">Is this attribute a designator?</label>    <input checked="checked" name="designator[0]" type="radio" value="0" id="designator[0]"> No 
       <input name="designator[0]" type="radio" value="1" id="designator[]"> Yes 
      </div> 
     </div> 
    </div> 

</fieldset> 

这里是我的jQuery:

$('.add_attr').click(function() { 
     // clone and add 
     $(".attr_entry:first").clone(true).removeClass('existent').insertAfter(".attr_entry:last"); 
    }); 

    $('.remove_attr').click(function() { 
     // remove entry 
     if($(this).parents('.attr_entry').first().hasClass('existent')) { 
      alert('You can not remove the first attribute entry.'); 
     } else { 
      $(this).parents(".attr_entry").first().remove(); 
     } 
    }); 

所以,当我克隆此,我想知道如何将名称属性更改为designator[1] ..因此添加一个。我不知道如何做到这一点,而仍然克隆和插入最后一个附加克隆后。

这里是我引用弄清楚如何接受单选按钮的数组的HTML:

Radio buttons + array elements

因为我需要知道我可以在我的PHP for循环做的属性和抢权指定者属于它。

感谢您的帮助!

+0

http://api.jquery.com/attr/ –

+0

我知道有生成的attr()方法。我只是不确定如何在克隆操作发生之前这样做,因为在克隆之后,它会删除第一个单选按钮选项并将其放在该单选按钮上,这样每个选项都不能被选中。 – user3130415

回答

3

您可以通过评估存在多少个$('.attr_entry')元素来获得新索引。然后,您可以合并find()prop()以设置单选按钮的名称。

修改你clone()线如下:

var newIndex = $('.attr_entry').length; 
$('.attr_entry:first').clone(true).removeClass('existent').insertAfter('.attr_entry:last').find('input[type="radio"]').prop('name', 'designator['+newIndex+']'); 

jsFiddle Demo

还请注意的是,id属性的元素应该是唯一的,所以你可能要考虑更新,在同一时间(使用相同的prop()方法)。

+0

他们是单选按钮,而不是复选框,因为我希望他们选择或者使其成为强制性的..而不是他们不必选择是或否与复选框..它是每个条目的强制性。 – user3130415

+0

对不起,我的坏。一秒钟,我正在为您找到正确的解决方案。 – BenM

+0

@ user3130415请参阅编辑。 – BenM

2

不太熟悉jquery中的克隆您可以使用attr()函数设置属性。

所以您的代码会是这个样子:

var designatorIndex = 0; 
$('.add_attr').click(function() { 
    // clone and add 

    var myVar = $(".attr_entry:first").clone(true).removeClass('existent'); 

    $(myVar).attr('name', 'designator' + designatorIndex); 
    $(myVar).id('designator' + designatorIndex); 
    designatorIndex++; 
    $(myVar).insertAfter(".attr_entry:last"); 
}); 
+0

这段代码没有任何作品。我甚至一次又一次地改变它,并且无法使它工作。 – user3130415