无法读取 属性 of nodeName undefined on jQuery validation with select2

Cannot read property of nodeName undefined on jQuery validation with select2

我正在尝试在我的 select2 下拉菜单中添加 jQuery 验证。但是,它一直导致"nodeName undefined"的javascript异常,我不确定哪里出了问题。

 $(".field-validation-required").each(function() {

     // output SELECT, if current html class is a select2 dropdown.
     console.log(this.nodeName); 

     $(this).rules('add', {
        required: true,
        messages: {
          required: "This field is required"
        }
     }); 
 });

我的 select2 下拉列表包含 class '.field-validation-required',我正在尝试对其应用一些 jQuery 验证。但似乎 $(this) 总是导致 "Cannot read property of nodeName undefined" 错误。

My select2 dropdown contains the class .field-validation-required and I am trying to apply some jQuery validation on it. But it seems $(this) always causes that "Cannot read property of nodeName undefined" error.

向我们展示相关的 HTML 标记;否则,我无法复制您的错误。


您的原始 select 是否包含独特的 name?这是插件强制要求的,缺失或重复的 name 可能是您的错误消息的根本原因。


您的 .field-validation-required class 是在原始 select 元素上还是在您动态创建的 Select2 元素上?

如果它在 select 元素上,那么它应该可以工作。如果它在 Select2 元素上,那么它将不起作用。

您只能对 selecttextarea、某些 inputcontenteditable 元素应用 jQuery 验证...没有别的。

定位原始隐藏的 select 元素而不是 Select2 元素。然后,由于插件将忽略所有隐藏元素,因此您需要将 ignore 选项设置为某些 jQuery 选择器,该选择器不会忽略隐藏的 select 元素。例如,ignore: [] 将告诉插件忽略任何内容并验证所有隐藏元素。


或者,您可以通过 class 或 HTML5 属性将 required 规则应用于原始 select 元素。您仍然需要如上所述设置 ignore 选项。

<select name="myselect" class="required" ....

<select name="myselect" required="required" ....