gpt4 book ai didi

javascript - 在 jQuery 中克隆 tr 和复选框事件

转载 作者:行者123 更新时间:2023-11-30 09:29:01 25 4
gpt4 key购买 nike

我必须克隆我的 <tr>我有如下代码所示的复选框列表,当我添加带有复选框列表的新行然后单击复选框以在文本框中显示值时 field_results该值不仅显示在尚未克隆的第一个文本框上。当我添加新的 tr,然后当我单击哪个 tr 中的哪个复选框列表时,它们将如何在同一 tr 中显示我的点击值。

$("#add-new").on("click", function () {                          
$tr = $(this).closest("tr").next().clone(true);
$tr.insertAfter($(this).closest("tr"));
});

$(document).ready(function () {
$checks = $('#mych_box :checkbox');
$checks.on('change', function () {
var string = $checks.filter(":checked").map(function (i, v) {
return this.value;
}).get().join(",");
console.log(string);
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<button type="button" id="add-new">Add New</button>
</td>
</tr>
<tr>
<td>
<input type="text" id="field_results" name="field_results[]"/><br>
<div class="multiselect" style="height: 100px;width: auto;" id="mych_box">
<label>
<input type="checkbox" id="virt_software_chb1" name="virt_software[]" value="White"/>White
<input type="checkbox" id="virt_software_chb2" name="virt_software[]" value="Red"/>Red
<input type="checkbox" id="virt_software_chb3" name="virt_software[]" value="Blue"/>Blue
</label>
</div>
</td>
</tr>

最佳答案

如上定义,在clone中使用true绑定(bind)默认事件,使用class代替id进行分组元素

        $(".virt_software_chb").on('change', function () {
var string = $(this).closest('td').find('.virt_software_chb').filter(":checked").map(function (i, v) {
return this.value;
}).get().join(",");
$(this).closest('td').find('.field_results').val(string);
});

$("#add-new").on("click", function () {
$tr = $(this).closest("tr").next().clone(true);
$tr.insertAfter($(this).closest("tr"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<button type="button" id="add-new">Add New</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="field_results" name="field_results[]"/><br>
<div class="multiselect" style="height: 100px;width: auto;" id="mych_box">
<label>
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="White"/>White
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="Red"/>Red
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="White"/>White
</label>
</div>
</td>
</tr>
</table>

关于javascript - 在 jQuery 中克隆 tr 和复选框事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com