如何将jQuery验证与“选择"菜单结合使用插入? [英] How can I use jQuery validation with the "chosen" plugin?

查看:54
本文介绍了如何将jQuery验证与“选择"菜单结合使用插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用选择插件输入了一些<select>输入,我想将其验证为必需"在客户端.由于选择"会隐藏实际的select元素并创建具有div和spans的小部件,因此本机HTML5验证似乎无法正常工作.表单不会提交(很好),但是不会显示错误消息,因此用户不知道出了什么问题(不好).

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验证插件(无论如何我最终还是打算使用该插件),但是到目前为止还没有任何运气.这是我的测试案例:

I've turned to the jQuery validation plugin (which I planned on using eventually anyways) but haven't had any luck so far. Here's my 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()行时,它工作正常.

This is letting the select through with an empty value, without validating or showing the error message. When I comment out the chosen() line, it works fine.

如何使用jQuery验证插件验证chosen()输入,并显示无效消息的错误消息?

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

推荐答案

jQuery validate会忽略隐藏元素,并且由于Chosen插件向选择中添加了visibility:hidden属性,请尝试:

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()函数之前添加此行.对我来说很好.

Add this line just before validate() function. It works fine for me.

这篇关于如何将jQuery验证与“选择"菜单结合使用插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆