我正在SAME FORM内使用重复表单字段。我将输入表单字段命名为数组,例如first_name[]
,gender[]
。
在这种情况下,单击单选按钮会影响其他重复表单组的单选按钮。
$('#repeatButton ').on('click', function() {
var repeater = $('#repeater .items').clone();
$('#repeater').append(repeater);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="repeater">
<div class="form-group items">
<input type="radio" value="male" name="gender[]"><label>Male</label>
<input type="radio" value="female" name="gender[]"><label>Female</label>
</div>
</div>
<input value="add" id="repeatButton">
</form>
答案 0 :(得分:3)
复选框根据name
属性进行分组。因此,您需要在每个name
组中使#repeater .items
唯一。在这种情况下,最简单的方法是将时间戳添加到该值。
请注意,您仅应clone()
而不是所有第一组,还应使用button
来触发添加新元素。我将收音机包裹在label
元素中,以允许用户也单击关联的文本。试试这个:
$('#repeatButton ').on('click', function() {
var $repeater = $('#repeater .items:first').clone();
var ts = (new Date()).getTime();
$repeater.find('input').attr('name', function(i, name) {
return ts + '_' + name;
});
$repeater.appendTo('#repeater');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="repeater">
<div class="form-group items">
<label>
<input type="radio" value="male" name="gender[]" />
Male
</label>
<label>
<input type="radio" value="female" name="gender[]" />
Female
</label>
</div>
</div>
<button type="button" id="repeatButton">Add</button>
</form>
答案 1 :(得分:1)
您可以执行以下操作。
$('#repeatButton ').on('click', function() {
var repeater = $('#repeater .items:first').clone();
$('#repeater').append(repeater);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="repeater">
<div class="form-group items">
<input type="radio" value="male" name="gender[]"><label>Male</label>
<input type="radio" value="female" name="gender[]"><label>Female</label>
</div>
</div>
<input value="add" id="repeatButton">
</form>
答案 2 :(得分:0)
$('#repeatButton ').on('click', function() {
var repeater = $('#repeater .items:first').html();
repeater = repeater+"<BR>";
$('#repeater').append(repeater);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="repeater">
<div class="form-group items">
<input type="radio" value="male" name="gender[]"><label>Male</label>
<input type="radio" value="female" name="gender[]"><label>Female</label>
</div>
</div>
<input value="add" id="repeatButton">
</form>