jQuery Validation for Radio Button and Check Box

By | September 26, 2012

Validation for radio button and check box in a webpage is important. Radio button and check boxes are used in poll, online test, registration form, etc. In each and every registration or any form, radio button & check box will have validation ( that is either javascript or jquery)




Stylesheet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<style type="text/css">
#dis
{
text-align:center;
height: 25px;
width: 250px;
background-color:#46DAFF;
color:#000;
}
#tex
{
width:120px;
float: left;
}
</style>

 

Below is the jquery validation for check box and radio button, both radio button and check box having same type of validation code.

if ($(“#gender:checked”).length == 0)  - This jquery code will be used for both the check box and radio button.

HTML, jQuery Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var gender=$('#gender').val();
var color=$('#color').val();
if ($("#gender:checked").length == 0){
$('#dis').slideDown().html('<span id="error">Please choose gender</span>');
return false;
}
if ($("#color:checked").length == 0){
$('#dis').slideDown().html('<span id="error">Please choose color</span>');
return false;
}

});
});
</script>
</head>
<body>

<fieldset style="width:290px;">
<form method="post" action="">
<label id="dis" style="width:250px;"></label><br>

<div id="tex">Gender:</div>
<input type="radio" name="gender" id="gender"> Male
<input type="radio" name="gender" id="gender"> Female<br>

<div id="tex">Color:</div>
<input type="checkbox" name="color[]" id="color"> Green
<input type="checkbox" name="color[]" id="color"> Blue
<input type="checkbox" name="color[]" id="color"> Blue

<center><input type="submit" name="submit" id="submit" /></center>
</form>
</fieldset>
</body>
</html>

3 thoughts on “jQuery Validation for Radio Button and Check Box

Leave a Reply to Fahim Faysal Cancel reply

Your email address will not be published. Required fields are marked *

dissident-bangalay