JQuery 验证下拉列表 [英] JQuery Validate Dropdown list

查看:26
本文介绍了JQuery 验证下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 此处 中的验证插件.我正在尝试强制用户在下拉列表中选择一个选项,所以这是我的列表 html:

I'm using the validation plugin from here. I'm trying force the user to select an option in the drop down list so here's my html for the list:

Select the best option<br/>
<select name="dd1" id="dd1">
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> <br/><br/>​

这里是 jquery 验证的内容:

And here's the the jquery validation stuff:

$("#everything").validate({
    onsubmit: true,
    rules: {
     dd1: {
      required: {
        depends: function(element) {
            return $("#dd1").val() == "none";
        }
      }
    },
    messages: {
     dd1: {
      required: "Please select an option from the list, if none are appropriate please select 'Other'",
     },
    }
});

我没有看到任何问题,但即使我从下拉列表中选择 none 并单击提交,它也不会验证它,因此不会显示任何消息.谁能告诉我我做错了什么?

I don't see any problems but even when the i select none from the drop down list and click submit, it won't validate it and so doesn't show any messages. Can anyone tell me what i'm doing wrong?

推荐答案

文档 对于 required() 状态:

要强制用户从选择框中选择一个选项,请提供一个空选项,例如 <option value="">Choose...</option>

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

通过在您的 标签中添加 value="none",您可以防止进行验证调用.您还可以删除自定义验证规则,从而简化您的代码.这是一个 jsFiddle,展示了它的实际效果:

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

如果您无法将 value 属性更改为空字符串,我不知道该告诉您什么...我找不到任何方法让它以其他方式进行验证.

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.

这篇关于JQuery 验证下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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