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

如果#category字段为空,我正在尝试下拉列表.

谢谢!

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 ATTEMPT#2:

$("#uploadDocsForm").validate({
    rules: {
        name: {
            required: true,cat_id: {
            required: {
                depends: function(element) {
                    return $("#category").val() == '';
                }
            }
        }
    },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,cat_id: 'Please select a <b>Category</b>.'
    }
});

依赖功能现在检查类别元素是否已填充,如果是,则需要第二个.否则它是可选的(意思可以填写).

用例:

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...