如何在选中框时验证其他字段。我试过以下但无济于事。我只希望在选择Horse或Pony时验证AnimalName2。 提前谢谢。
HTML:
<select class="vars" data-hint="" name="Registration2">
<option data-price="0.00" selected="selected" value="">
None
</option>
<option data-price="5.00" value="Horse">
Horse
</option>
<option data-price="5.00" value="Pony">
Pony
</option>
</select> <span class="clear">clear</span>
<div class="quarter">
<label style="font-weight: bold; display: inline;">Name</label><br>
<input autocomplete="off" data-hint="" maxlength="254" name="AnimalName2"
placeholder="" type="text">
</div>
我正在使用jquery.validate.min.js
<script>
(function($, W, D) {
var JQUERY4U = {};
JQUERY4U.UTIL = {
setupFormValidation: function() {
//form validation rules
$("#addriderform").validate({
rules: {
AnimalName2: {
required: "Registration2:selected"
},
agree: "required"
}
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
答案 0 :(得分:1)
将ID提供给Dropdown,使用jQuery validate的depends
参数:
工作小提琴HERE
HTML
<form id="addriderform" method="post">
<select class="vars" data-hint="" name="Registration2" id="Registration2">
<option data-price="0.00" selected="selected" value="">
None
</option>
<option data-price="5.00" value="Horse">
Horse
</option>
<option data-price="5.00" value="Pony">
Pony
</option>
</select>
<span class="clear">clear</span>
<div class="quarter">
<label style="font-weight: bold; display: inline;">Name</label><br>
<input autocomplete="off" data-hint="" maxlength="254" name="AnimalName2"
placeholder="" type="text"/>
<input type="submit"/>
</div>
</form>
的jQuery
//form validation rules
$("#addriderform").validate({
rules: {
AnimalName2: {
required: {
depends: function(element) {
if($("#Registration2").val() != "")//If Pony or Horse selected
{
return true;
}
else
{
return false;
}
}
}
},
//Registration2:{required:true}
},
messages: {
AnimalName2: {
required: "Please fill TEXTBOX"
},
Registration2:{
required: "Please select DROPDOWN ."
}
},
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
},
submitHandler: function(form) {
form.submit();
}
});
它表示“AnimalName2”的必需属性此文本框取决于其中的条件。 请参阅下文,检查是否选择“无”.IF从Dropdown中选择无,返回false,表示必需属性变为false,否则变为true,因此验证适用于文本框。
function(element) {
if($("#Registration2").val() != "")//If Pony or Horse selected
{
return true;
}
else
{
return false;
}
}
有关详情,请查看HERE