How to validate if all check boxes are ticked in jQuery?

Posted by Jude on Stack Overflow See other posts from Stack Overflow or by Jude
Published on 2012-09-27T03:22:38Z Indexed on 2012/09/27 3:37 UTC
Read the original article Hit count: 88

Filed under:
|
|

I am a beginner in jQuery and I was wondering how to validate the form before submission specifically for check boxes.

I am creating a simple check list form where my user would tick a check box if he finished that step. What I am planning to do is that, the script would prevent the form submission if there is an "unticked" checkbox and highlight it with a color.

Here's my code :

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>checkbox</title>
<style>
.error {
    background-color:#F00;
}
.valid {
    background-color:#0F0;
}
</style>
<script type="application/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js">    </script>
<script type="application/javascript">
function validateAll() {
    $(".tick").change(function(){
        if ($('.tick:checked').length == $('.tick').length) {
            $('#container').removeClass();
            $('#container').addClass('error');
        } else {
            $('#container').removeClass();
            $('#container').addClass('valid');
        }
});    
}    
</script>
</head>

<body>
<div id="container"><input class="tick" id="option1" type="checkbox"></div>
<div id="container"><input class="tick" id="option1" type="checkbox"></div>
<input id="button" type="button" onClick="validateAll();" value="check">
</body>
</html>

So what I am trying to do here is when the user clicks the button, the script will highlight all the unchecked check box with red and highlight all checked with green.

However, my script is not functioning. What is wrong with my script? Any suggestions on a more efficient way to do this?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery