我在这里有 1 个问题:如何在 JavaScript 中获取复选框值。
- 在帮助下,它工作得很好。但是,当我向 DataTable 添加按钮:['colvis'] 时,单击复选框事件似乎无法正常工作。我在 DataTable 论坛上寻求帮助,但无济于事。
代码:
<input id="listvalue" name="selectedCB">
<table id="datatest" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th class="no-sort checkboxor">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" /> #
</th>
<th class="no-sort">IDtest</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tycheck">
<input type="checkbox" name="checkAll" value="2" class="checkSingle" />
</td>
<td>1</td>
</tr>
<tr>
<td class="tycheck">
<input type="checkbox" name="checkAll" value="1" class="checkSingle" />
</td>
<td>2</td>
</tr>
</tbody>
</table>
$(document).ready(function () {
$('#datatest').DataTable({
buttons: [
'colvis'
]
});
});
var idsArr = [];
var displayField = $('input[name=selectedCB]');
var checkboxes = Array.from($(".tycheck input[type=checkbox]"));
function toggle(source) {
var values = checkboxes.map(x => {
x.checked = source.checked;
return source.checked ? x.value : '';
}).join(source.checked ? ',' : '');
displayField.val(values);
}
function printChecked() {
var values = checkboxes.filter(x => x.checked).map(x => x.value);
displayField.val(values);
}
$.each(checkboxes, function () {
$(this).change(printChecked);
})