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

[code type=css]

<style type=”text/css”>
#dis
{
text-align:center;
height: 25px;
width: 250px;
background-color:#46DAFF;
color:#000;
}
#tex
{
width:120px;
float: left;
}
</style>

[/code]

 

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

[code type=html]

<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>

[/code]

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

  1. aash

    How can you give the ‘id’ attribute to the same value? Id attribute is unique, instead of that you can use ‘class’ attribute.

    Reply

Leave a Reply to padma Cancel reply

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

aspersive-cuirie