Checkbox always returns false when I do . is(":checked");

Asked

Viewed 742 times

-2

Code is this:

<script>
$(document).ready(function () {
    alert("funfo");
    $("#segunda").click(function () {
        var check = $("#segunda").is(":checked");
        if (check == "true") {
            alert("true");
        } else {
            alert("false");
        }
        alert(check);
    });
});
</script>

Problem is, the guy selects the checkbox, returns false, he clears, returns false.. whereas true returns when the box is selected, and false when it is desiccated..

I used a alert(check); and he returns true, and false, for marked and not marked, exactly as it was to do, but in checking the IF it always returns an option, which in case is false..

  • 1

    You are checking whether the var check is equal to "true"(string) instead of testing if it is true (note without the quotes)

  • True. I thought that, a variable receiving a value, the value turned into string, but since there is no variable type declaration, I think that’s why it ends up "fitting" to what was!!

1 answer

2


$(document).ready(function () {
    alert("funfo");
    $("#segunda").click(function () {
        var check = this.checked;
        if (check) alert("true");
        else alert("false");
        alert('O valor do check é: ' + check);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="segunda" />

When you use .is(":checked") this will return a Boolean. Ie true or false. In your comparison you’re comparing it to "true". When using quotes you are using the String and not Boolean type. So the comparison should be if (check == true){. Actually this comparison is unnecessary, just do if (check){.

Another aspect that can change (and changed in the answer example code) is that you don’t need $("#segunda").is(":checked"), can use pure Javascript without jQuery, (this.checked) since you are looking for the checked of the element that was clicked. (The less jQuery the better...).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.