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 one:
let $cbs = $(".myCheckBox").change(function() {
if ($cbs.is(":checked")){
// disable #confirmButton if at least one checkboxes were checked
$("#confirmButton").prop("disabled", false);
} else {
// disable #confirmButton if all checkboxes were unchecked
$("#confirmButton").prop("disabled", true);
}
});
讨论(0)
-
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.
讨论(0)
-
Try this:
$('tbody').click(function () {
if ($('.myCheckBox:checked').length >= 1) {
$('#confirmButton').prop("disabled", true);
}
else {
$('#confirmButton').prop("disabled", false);
}
});
DEMO
讨论(0)
-
Add an event handler that fires when a checkbox is changed, and see if there are any checked boxes, and set the disabled property appropriately :
var boxes = $('.myCheckBox');
boxes.on('change', function() {
$('#confirmButton').prop('disabled', !boxes.filter(':checked').length);
}).trigger('change');
FIDDLE
讨论(0)
- 热议问题