1

I have a loop which is supposed to go around four check boxes I have and for every one that's checked false, it should add one onto a count. However, it doesn't work. It seems to only loop around one checkbox. Can anybody help me find out why?

JQuery:

 $("#CreateUserButton").on('click', function () {
            var rt = false;
            var count = 0;
            $(".RoleCheck").each(function () {
                if ($(".RoleCheck").prop('checked') == false) {
                        count = count + 1;
                        alert("Added one");
                }
            });
            if (count == 4) {
                alert("All four been detected");
                $("#ModalErrorText").html("Error : A Role has not been selected.");
                rt = false;
            }
            $("#ErrorBox").prop('hidden', rt);
            return rt;
        });

HTML:

<div class="col-md-10" id="createButton">
                @foreach (var item in (SelectList)ViewBag.RoleId) {
                    <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline RoleCheck" />
                    @Html.Label(item.Value, new { @class = "control-label" })
                }
            </div>

I know that it has something to do with the foreach loop in the HTML to create the select boxes.

2 Answers 2

5

Execute loop in this context, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

$(".RoleCheck").prop('checked') will always return the checked state of first checkbox.

$(".RoleCheck").each(function () {
    //this.checked can also be used
    if ($(this).prop('checked') == false) {
            count = count + 1;
            alert("Added one");
    }
});

However, loop can be simplified using length property.

var count = $(".RoleCheck:not(:checked)").length;
Sign up to request clarification or add additional context in comments.

2 Comments

@AndrewKilburn, this refers to current element which in the each itaration
Thank you for the answer and explanation
0
var count=$(".RoleCheck").not(":checked").length

:checked selector can find all checked checkbox,
not() function can except some elements from an arrary of elements

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.