我是jquery validate()插件的新手,我有点迷失在这里。所以,我想要做的是检查所选单选按钮是否等于变量:
所以,让我说我有这样的形式:
<input name = "radio_btns" value = "five" type = "radio">5
<input name = "radio_btns" value = "eight" type = "radio">8
我想验证它以确保选择“五”选项,并且我想使用Javascript变量。我试过这个,很明显它不会起作用,无论如何:
<script>
var required_answer = "five";
$(document).ready(function(){
$('#theform').validate({
rules: {
radio_btns: {
required: true,
equalTo: required_answer <--- problem here ¬.¬
}
...
</script>
提前感谢您的帮助。
答案 0 :(得分:1)
工作fiddle
使用以下自定义方法
// HTML
<form id="theform">
<input name = "radio_btns" value = "five" type = "radio"/>5
<input name = "radio_btns" value = "eight" type = "radio"/>8
<input type="submit"/>
</form>
// jQuery part
在这里检查选择的单选按钮的值是&#34;五&#34; ,如果它的五个然后返回TRUE否则为FALSE。因此,如果返回true,则提交表格(或者说如果选择五个),否则不要。
$(document).ready(function(){
jQuery.validator.addMethod("selectFive", function(value, element)
{ var required_answer = "five";
if(value == required_answer) {
return true;
}else{
return false;
}
}, "Please select five.");
// validate the comment form when it is submitted
$("#theform").validate({
errorElement: 'div',
rules: {
radio_btns: {
required: true,
selectFive: true
}
},
messages: {
radio_btns: {
required: "Please select."
}
},
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
},
submitHandler: function(form) {
jQuery('input[type=submit]', form).attr('disabled', 'disabled');
form.submit();
}
});
});