首页 文章

使用单选按钮克隆表单

提问于
浏览
0

在jQuery中克隆表单,例如在具有多个人的访客列表上创建RSVP选项,相对简单 .

$(selector).clone().insertAfter(selector:last)

输入也相对容易,通过将 true 传递给 clone() 方法,可以复制方法或属性 . 要处理多个输入,您可以将 [] 追加到输入名称的末尾:

<input type="text" name="email_address[]"/>

但是,对于 radio 类型的 <input> 元素,这会变得更加复杂,因为您通常会使用这些元素来表示选择:

<input type="radio" name="choice" value="1"/> <input type="radio" name="choice" value="2"/>

添加方括号语法会进一步混淆事物,因为仍有多个值,并且某些浏览器现在可能允许不同的选择:

<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>
<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>

我们如何以一种允许轻松克隆而不使后端难以解析单选按钮的方式来解决这个问题?

1 回答

  • 0

    事实证明这可以通过一点RegEx乐趣来实现!

    首先将数值添加到第一个输入元素:

    <input type="radio" name="choice[0]" value="1"> <input type="radio" name="choice[0]" value="2">
    

    现在在你的JavaScript中

    $(selector).clone().insertAfter(selector:last)
    .find('input[type="radio"]').each(function(){
        var name=$(this).attr('name');
        $(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));
    });
    

    这为每个元素创建了一个简单的数字增量,与其兄弟姐妹一致 .

相关问题