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?
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.