Check if field is required?

雨燕双飞 提交于 2021-01-20 12:36:08

问题


I need to find all required fields in given form using jquery. I was using this syntax:

$('input[required],select[required]')

This was doing job, but now I started using jQuery Validation Plugin. As i understood plugin would not add 'required' attribute to field, and thats why above script is failing to find required fields. Is it possible select required field when using jQuery Validation Plugin?


回答1:


As I understood plugin would not add 'required' attribute to field, and thats why above script is failing to find required fields.

The jQuery Validate plugin does not dynamically add or remove attributes from the input elements. It only adds/removes a class depending on whether the field is valid or invalid.

Is it possible select required field when using jQuery Validation Plugin?

Not directly. There is nothing unique about an input when the field has the "required" rule declared by the plugin's settings.

However, with this plugin, rules can be declared on the fields using several other methods... just two examples follow.

Instead of declaring the required rule via the rules object within .validate(), simply add the HTML5 required attribute to the fields yourself. The jQuery Validate plugin will work by picking up this HTML5 attribute and assigning the required rule to the field for validation.

<input type="text" name="foo" required />

OR

<input type="text" name="foo" required="required" />

and you don't need to specify the element itself in the selector, just the attribute, like this...

$('[required]')

OR

$('[required="required"]')

You can also assign the rule via a class...

<input type="text" name="bar" class="required" />

then you can easily select all elements with this class...

$('.required')

This demo shows three different ways to assign the required rule.

DEMO: jsfiddle.net/fg25jsw3/



来源:https://stackoverflow.com/questions/42760281/check-if-field-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!