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>Untitled Document</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">
$('#button').on('click', function() {
var $checkboxes = $('.container [type=checkbox]');
$checkboxes.filter(':checked').parent().removeClass('error').addClass('valid');
$checkboxes.not(':checked').parent().removeClass('valid').addClass('error');
});
</script>
</head>
<body>
<div class="container">
<input class="tick" id="option1" type="checkbox">
</div>
<div class="container">
<input class="tick" id="option1" type="checkbox">
</div>
<input id="button" type="button" 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?
Try the following:
http://jsfiddle.net/2dcPE/
Note that your markup is not valid, IDs must be unique.