Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through checkboxes by classname in jquery

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);

            }
like image 960
user819774 Avatar asked Mar 10 '23 16:03

user819774


1 Answers

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>
like image 112
Neil Avatar answered Apr 06 '23 02:04

Neil