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.
-
Try this:
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:
- 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.
- 热议问题