I am trying to add jQuery validation on my select2 drop-down. However, it keeps causing the javascript exception of "nodeName undefined", I am not sure what went wrong.
$(".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"
}
});
});
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.
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.
Show us the relevant HTML markup; otherwise, I cannot duplicate your error.
Does your original select
contain a unique name
? This is mandated by the plugin and a missing or duplicate name
may be the root cause of your error message.
Is your .field-validation-required
class on the original select
element or on your dynamically created Select2 elements?
If it's on the select
element, then it should work. If it's on the Select2 element, then it will not work.
You can only apply jQuery Validate to select
, textarea
, certain input
, and contenteditable
elements... nothing else.
Target the original hidden select
element instead of the Select2 element. Then since the plugin will ignore all hidden elements, you'll need to set the ignore
option to some jQuery selector that does not ignore your hidden select
element. For example, ignore: []
will tell the plugin to ignore nothing and validate all hidden elements.
Alternatively, you can apply the required
rule to your original select
element by class or HTML5 attribute. You'll still need to set the ignore
option as described above.
<select name="myselect" class="required" ....
or
<select name="myselect" required="required" ....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.