jQuery validation issue
I'm trying to get jQuery validate to work with my radio button form. However, I'm having trouble with getting it to work, the validation functionality isn't working at all, this is the code I'm working with:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#formq").validate();
});
</script>
<style type="text/css">
<!--
label.error {display: none;}
//-->
</style>
</head>
<body>
<form id="formq" name="formq" action="check.php" method="post">
<fieldset>
<input type="hidden" name="check_submit" value="1" />
<label for="radio-1" tabindex="1" class="circle">Circle</label>
<input type="radio" name="radio-button" id="radio-1" value="Circle" validate="required:true" />
<label for="radio-2" tabindex="2" class="pentagon">Pentagon</label>
<input type="radio" name="radio-button" id="radio-2" value="Pentagon" />
<label for="radio-3" tabindex="3" class="triangle">Triangle</label>
<input type="radio" name="radio-button" id="radio-3" value="Triangle" />
<label for="radio-4" tabindex="4" class="hexagon">Hexagon</label>
<input type="radio" name="radio-but开发者_开发技巧ton" id="radio-4" value="Hexagon" />
<label for="radio-5" tabindex="5" class="square">Square</label>
<input type="radio" name="radio-button" id="radio-5" value="Square" />
<label for="radio-6" tabindex="6" class="octagon">Octagon</label>
<input type="radio" name="radio-button" id="radio-6" value="Octagon" />
<label for="radio" class="error">Please select your gender</label>
<input class="submit" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
</html>
Names with "-"are not working. I didn't check the documentation, but the code below worked
$.validator.setDefaults({
submitHandler: function() { alert("submitted!"); }//gives an alert messagem when submitted
});
$(document).ready(function() {
$("#formq").validate({
rules: {
radiobutton: "required"
},
messages: {//to use custom messages
radiobutton: "This is needed, buddy!"
}
});
});
If you use the way you did before, $("#formq").validate(), you can also use classes:
<input type="radio" class="required" />
You haven't specified any rules for jQuery validate. Do it using CSS, jquery metadata, or in the function call. E.g. (not tested):
$("#formq").validate({ rules:
{
"radio-button" : { required : true }
}
});
With this you can test if is checked or not and which one is checked:
$('.submit').bind('click',function() {
if($("#formq input:radio").is(':checked')) {
alert('true, value = '+$('#formq input:radio:checked').val());
} else {
alert('false');
}
});
精彩评论