gpt4 book ai didi

如果字段为空,则需要 Jquery 验证下拉列表

转载 作者:行者123 更新时间:2023-12-03 22:04:21 25 4
gpt4 key购买 nike

如果 #category 字段为空,我会尝试将下拉列表设为必需。

谢谢!

JQUERY 尝试#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:

$("#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 函数现在检查类别元素是否已填充,如果是,则需要第二个元素。否则是可选的(意思是可以填充)。

用例:

  • 类别已填,cat_id 为空:无效
  • 已填写类别,已填写cat_id:有效
  • 类别为空,cat_id 为空:有效
  • 类别为空,cat_id 已填充:有效

关于如果字段为空,则需要 Jquery 验证下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5957440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com