I need to loop through the all checkboxs to set the button disable or not. If one of the checkbox is checked, then the button is enable. However it looks like my code didn't loop through the checkbox. The alert inside the each function doesn't shown.I found the looping method on How to loop through group of check boxes that have same class name?
There is my code:
function setButton() {
alert('line 24');
var blnDisable = true;
//https://stackoverflow.com/questions/35506843/how-to-loop-through-group-of-check-boxes-that-have-same-class-name
$('.chkItem').each(function (index, obj) {
if (obj.checked == true) {
alert('line 30');
blnDisable = false;
}
});
alert('disable=' + blnDisable);
$("#btnDownload").attr("disabled", blnDisable);
}
This will make it check to see if any of the check boxes are checked. If so, it will enable the check box, if not it will disable it. Lastly, I assigned it to a function so it can be run on page load. This is important so it will automatically check to see whether the download button should be enabled on page laod.
<input type="checkbox" class="chkItem" />one<br />
<input type="checkbox" class="chkItem" />two<br />
<input type="checkbox" class="chkItem" />three<br />
<button id="btnDownload">download</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var checkButton = function () {
blnDisable = true;
$('.chkItem').each(function (index, obj) {
if (this.checked === true) {
blnDisable = false;
}
});
$("#btnDownload").attr("disabled", blnDisable);
};
$(".chkItem").on("change", checkButton);
checkButton();
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With