Zychoo
Zychoo

Reputation: 625

Checkbox form validation not working

I am trying to prevent form from validation if checkbox is not checked with following code:

<script>
$(function() {

    $("#form").submit(function(e) {
        console.log("test1");
        if(!$('input[type="checkbox"]:checked')) {
            alert("Check the checkbox or you will die.");
            return false;
        }
        console.log("test2");
        return true;
    });
});
</script>

I don't know why my death threat doesn't appear. console.log(test1) is working. As well as test2.

Can you please guide me a little bit so I can see my mistake?

Upvotes: 0

Views: 297

Answers (2)

Barmar
Barmar

Reputation: 781096

jQuery selectors return a collection, not true/false. You need to test the size of the collection:

if ($(':checkbox:checked').length = 0) {
    alert("Check the checkbox or you will diet.");
    return false;
}

Upvotes: 0

taxicala
taxicala

Reputation: 21759

Replace:

!$('input[type="checkbox"]:checked')

With:

$("input:checked").length === 0

That way you are validating that there is at least one input checked in the DOM. I strongly recommend using an ID or CLASS to narrow the scope of the validation though.

Upvotes: 2

Related Questions