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

-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 , it unchecks, returns false .. being true returns when the box is selected, and false when deselected ..

I've used alert(check); and it returns true , and false , for checked and unchecked, exactly as it was to do, but in checking IF it always returns an option, which in this case is false ..

    
asked by anonymous 03.11.2014 / 01:14

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><inputtype="checkbox" id="segunda" />

When you use .is(":checked") this will return a Boolean. That is true or false . In your comparison you compare with "true" . When using quotes it is using the String type and not Boolean. So the comparison should be if (check == true){ . In fact this comparison is unnecessary, just make if (check){ .

Another thing that can change (and I changed the code in the response example) is that it does not need $("#segunda").is(":checked") , you can use pure JavaScript without jQuery, (this.checked) since it is looking for checked of the element that was clicked. (The less jQuery the better ...).

    
03.11.2014 / 07:56