jquery 验证插件上的自定义验证,需要计算多选中的元素

发布于 2024-08-30 02:42:57 字数 735 浏览 1 评论 0原文

我有一个多重选择,我需要强制用户选择最多两个选项,仅此而已。

我正在尝试这个:

jQuery.validator.addMethod("morethantwo", 
    function(value, element) {

        var foo = [];
        $(element+' :selected').each(function(i, selected){
            foo[i] = $(selected).text();
            alert(foo[i]);
        });
        return true;

    },"Max two options." 
);

问题是我收到一个:

uncaught exception: Syntax error, unrecognized expression: [object HTMLSelectElement]

错误。虽然如果我这样做:

$(element).each(function(i, selected){
            foo[i] = $(selected).text();
            alert(foo[i]);
        });

它有效,但我得到了选择中的所有选项。这是为什么?这是正确的路吗?有没有更好的方法来进行此类检查?

非常感谢!

I have a multiple select, and I need to force the user to choose maximum two options, nothing more.

I'm trying this:

jQuery.validator.addMethod("morethantwo", 
    function(value, element) {

        var foo = [];
        $(element+' :selected').each(function(i, selected){
            foo[i] = $(selected).text();
            alert(foo[i]);
        });
        return true;

    },"Max two options." 
);

The problem is that I get a:

uncaught exception: Syntax error, unrecognized expression: [object HTMLSelectElement]

error. While if I do this:

$(element).each(function(i, selected){
            foo[i] = $(selected).text();
            alert(foo[i]);
        });

It works but I get all the options in the select. Why is that? Is this the correct road to walk? Are there better ways to do this kind of check?

Thank you very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天赋异禀 2024-09-06 02:42:57

要回答它损坏的原因, element 是一个 DOM 元素,而不是字符串,因此在该代码中,您尝试执行 DOMElement+string...但事实并非如此。不工作:)而是包装 DOM 元素并使用 .find().children() 获取选项。

知道它为何损坏后,您可以像这样编写规则来检查所选选项:

jQuery.validator.addMethod("maxtwo", function(value, element) {
  return $(element).find(":selected").length <= 2;
},"Max two options.");

在此处查看上述代码的演示

如果您严格处理

 return $(element).val().length <= 2;

因为.val() 返回一个数组。

To answer the why it's breaking, element is a DOM element, not a string, so in that code you're trying to do DOMElement+string...which doesn't work :) Instead wrap the DOM element and use .find() or .children() to get the options.

Knowing why it broke, you can write your rule like this to check the selected options:

jQuery.validator.addMethod("maxtwo", function(value, element) {
  return $(element).find(":selected").length <= 2;
},"Max two options.");

Check here for a demo of the above code

If you're strictly dealing with a <select multiple> you could do this as well:

 return $(element).val().length <= 2;

Since .val() returns an array in that case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文