我只想在“select1”字段中选定的文本为“其他”时才需要“其他”字段,我正在尝试的规则是:other: { required: function(element){ return $("#select1 option:selected").text() == "Other"; } }
难道我做错了什么?这是代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery- validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('form:first').validate({
rules: {
cname: {
required: true,
},
select1: { valueNotEquals: "0" }
},
other: {
required: function(element){
return $("#select1 option:selected").text() == "Other";
}
},
messages: {
cname: "Please enter a valid naaaammmeeee.",
select1: "Please choose a valid option",
other: "Please enter a valid other value",
},
});
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
});
</script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="cname"/>
</p>
<p>
<select name="select1" id="select1">
<option value="0">Please choose a value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">Other</option>
</select>
</p>
<p>
<label for="other">Other</label>
<em>*</em><input id="other" name="other"/>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
有多个问题主要与 JSON 格式相关:
-
额外一个closing bracket
here:
select1: { valueNotEquals: "0" }
},
-
One closing bracket
结尾处失踪了rules
定义和开始之前messages
定义
return $("#select1 选项:已选择").text() == "其他";
}
}},
消息:{
Extra comma
每个选项的末尾都是不必要的
-
validate.js 路径中的空格(这可能是问题本身中的拼写错误)
这是更正后的代码:
...
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('form:first').validate({
rules: {
cname: { required: true },
select1: { valueNotEquals: "0" },
other: { required: function(element){
return $("#select1 option:selected").text() == "Other";
}
}
},
messages: {
cname: "Please enter a valid naaaammmeeee.",
select1: "Please choose a valid option",
other: { required: "Please enter a valid other value"}
}
});
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)