如果字段为空,则需要jQuery Validate下拉列表 [英] Jquery Validate dropdown required if field empty
本文介绍了如果字段为空,则需要jQuery Validate下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果#category字段为空,我试图将下拉列表设为必需.
I'm trying to make the dropdown required if the #category field is empty.
谢谢!
JQUERY尝试#1:
JQUERY ATTEMPT #1:
$("#uploadDocsForm").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 255
},
cat_id: {
required: function(element) {
return $("#category").val() == '';
}
}
},
messages: {
name: 'Please enter a <b>Document Name</b>.',
cat_id: 'Please select a <b>Category</b>.'
}
});
JQUERY尝试#2:
JQUERY ATTEMPT #2:
$("#uploadDocsForm").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 255
},
cat_id: {
required: {
depends: function(element) {
return $("#category").val() == '';
}
}
}
},
messages: {
name: 'Please enter a <b>Document Name</b>.',
cat_id: 'Please select a <b>Category</b>.'
}
});
HTML:
<form name="uploadDocsForm" id="uploadDocsForm">
<label for="name">Document Name</label>
<input name="name" id="name" type="text" class="textbox"/>
<label for="cat_id">Category</label>
<select name="cat_id" id="cat_id" class="dropdown">
<option selected>Please Select Category</option>
<option>------------------------</option>
<option value="1">test cat</option>
</select>
<label for="category">New Category</label>
<input name="category" id="category" type="text" class="textbox"/>
</form>
推荐答案
$("#uploadDocsForm").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 255
},
cat_id: {
required: {
depends: function(element) {
return $("#category").val() == '';
}
}
}
},
messages: {
name: 'Please enter a <b>Document Name</b>.',
cat_id: 'Please select a <b>Category</b>.'
}
});
depends函数现在检查category元素是否已填充,如果是,则第二个元素是必需的.否则,它是可选的(可以填充).
The depends function now checks if the category element is filled, and if so the second is required. Otherwise it is optional (meaning can be filled).
用例:
- 类别已填写,cat_id为空:无效
- 类别已填充,cat_id已填充:有效
- 类别为空,cat_id为空:有效
- 类别为空,填充了cat_id:有效
这篇关于如果字段为空,则需要jQuery Validate下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文