7

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

            }
4
  • obj will be a jQuery object - jQuery objects don't have a checked property - use an instance of this - if (this.checked) Commented Mar 9, 2017 at 20:47
  • @tymeJV Im pretty sur obj will be an HTML element. @op When is setButton called? Commented Mar 9, 2017 at 20:51
  • or the built-in jquery "prop" function: if(obj.prop("checked")) Commented Mar 9, 2017 at 20:51
  • @Karl-AndréGagnon -- Ahh yep you're right, not sure why I thought it'd be a jQ object. Commented Mar 9, 2017 at 20:58

1 Answer 1

10

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.