I have some <select> inputs using the chosen plugin that I want to validate as "required" on the client side. Since "chosen" hides the actual select element and creates a widget with divs and spans, native HTML5 validation doesn't seem to work properly. The form won't submit (which is good), but the error message is not shown, so the user has no idea what's wrong (which is not good).

我已经求助于jQuery验证插件(无论如何我都计划最终使用它),但到目前为止还没有任何收获.这是我的test case分:

<form>
    <label>Name: <input name="test1" required></label>
    <label>Favorite Color:
        <select name="test2" required>
            <option value=""></option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
        </select>
    </label>
    <input type="submit">
</form>
$(document).ready(function(){
    $('select').chosen();
    $('form').validate();
});

这是在不验证或显示错误消息的情况下,以空值让select通过.当我注释掉chosen()行时,效果很好.

How can I validate chosen() inputs with the jQuery validation plugin, and show the error message for invalid ones?

推荐答案

jQuery validate ignores the hidden element, and since the Chosen plugin adds visibility:hidden attribute to the select, try:

$.validator.setDefaults({ ignore: ":hidden:not(select)" }) //for all select

OR

$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" }) //for all select having class .chosen-select

validate()函数之前添加这一行.这对我很管用.

Jquery相关问答推荐

JQuery日期 Select 器未设置从jQuery中 Select 的月份起90天或3个月

将 jquery 元素转换为 html 元素

在正则表达式字符括号中包含连字符?

jQuery / Ajax - $.ajax() 将参数传递给回调 - 使用好的模式?

组合数组时无法读取未定义的属性推送

jquery - 单击事件不适用于动态创建的按钮

jQuery增量读取AJAX流?

谷歌图表重绘/zoom 窗口调整大小

Jquery,清除/清空 tbody 元素的所有内容?

停止输入/书写后如何触发输入文本中的事件?

如何通过js打开 Select 文件对话框?

JQuery - 如何根据值 Select 下拉项

如何在 JQuery 中 Select 除单击元素之外的所有类?

如何使用 jQuery 或纯 JS 重置所有复选框?

jQuery select2 获取 Select 标签的值?

使用 jQuery 在 Select 列表中隐藏选项

jquery $(window).height() 正在返回文档高度

如何判断值是否为 JSON 对象?

jQuery,简单的轮询示例

jQuery中的wait()或sleep()函数?