如果未选中所有复选框,则禁用按钮;如果至少选中了一个复选框,则启用该按钮 [英] Disable button if all checkboxes are unchecked and enable it if at least one is checked
问题描述
我有一张桌子,每一行都有一个复选框,下面有一个按钮.如果要至少选中一个复选框,我想禁用该按钮.
I have a table with a checkbox in each row and a button below it. I want to disable the button if at least one checkbox is checked.
<tbody>
<tr>
<td>
<input class="myCheckBox" type="checkbox"></input>
</td>
</tr>
</tbody>
<button type=submit id="confirmButton"> BUTTON </button>
我为完成此任务而想到的jQuery如下:
The jQuery I came up with to accomplish this is the following:
$('tbody').click(function () {
$('tbody tr').each(function () {
if ($(this).find('.myCheckBox').prop('checked')) {
doEnableButton = true;
}
if (!doEnableButton) {
$('#confirmButton').prop('disabled', 'disabled')
}
else {
$('#confirmButton').removeAttr("disabled");
}
});
});
自然,这是行不通的.否则我不会在这里.它所做的只是仅响应最低的复选框(例如,选中/取消选中最低按钮时,启用/禁用该按钮).
Naturally, this does not work. Otherwise I would not be here. What it does do is only respond to the lowest checkbox (e.g., when the lowest button is checked/unchecked the button is enabled/disabled).
我在此处做了一个JSFIddle,尽管它没有表现出与本地相同的行为.
I made a JSFIddle here although it does not show the same behaviour as locally.
有什么我知道该如何响应所有复选框并禁用所有按钮的按钮吗?
Does any know how I can accomplish that it responds to all checkboxes and disables the button if they are ALL disabled?
推荐答案
尝试一下:
var checkBoxes = $('tbody .myCheckBox');
checkBoxes.change(function () {
$('#confirmButton').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
checkBoxes.change(); // or add disabled="true" in the HTML
演示
说明,我所做的更改:
Demo
Explanation, to what I changed:
- 缓存复选框元素列表/数组以使其更快一点:
var checkBoxes = $('tbody .myCheckBox');
- 删除了
if/else
语句,并使用> prop() 来在disable = true/false之间切换. - 使用
- Cached the checkbox element list/array to make it a bit faster:
var checkBoxes = $('tbody .myCheckBox');
- removed the
if/else
statement and used prop() to change between disable= true/false. - filtered the cached variable/array
checkBoxes
using filter() so it will only keep the checkboxes that are checked/selected. - inside the second parameter of prop added a condition that will give
true
when there is more than one checked checkbox, or false if the condition is not met.
这篇关于如果未选中所有复选框,则禁用按钮;如果至少选中了一个复选框,则启用该按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!