How can I cross-browser detect input fields with the 'required' attribute in jQuery?

删除回忆录丶 提交于 2019-12-04 03:39:56

问题


I am running into a slight validation issue with the Boolean required attribute on form fields.

I am marking up my fields as such:

<label for="email">Email Address:</label>
<input value="" type="email" name="email" id="email" required />

But trying to find all required fields using jQuery and adding them to an array seems problematic due to detection issues.

The following only works in Firefox (Gecko) $(':input[required=""]') but returns nothing in Webkit (Safari, Chrome).

Webkit on the other hand return all required fields if I run $(':input[required]') or $(':input[required="true"]'), but when this runs through Gecko it doesn't return the required fields.

What am I doing wrong here? Last I checked the input attribute was simply required and neither required="required" nor required="true".

Is there a better way of detecting all the required fields using javascript/jQuery?


回答1:


It may be a bad workaround, but have your tried a multiple selector?

$(':input[required=""],:input[required]')



回答2:


Here you go. This will output an array with all required fields.

<input value="" type="email" name="email" id="email" required/>
<input value="" type="email" name="email1" id="email1"  required/>
<input value="" type="email" name="email2" id="email2"/>

<script type="text/javascript">
var x = $('input[required]').get();
console.log(x); // x will contain an array of required inputs [input#email, input#email1]
</script>



回答3:


with bootstrap 3, you can do:

$('input[required]')
    .closest(".form-group")
    .children("label")
    .append(" <i class='fa fa-asterisk'></i>");


来源:https://stackoverflow.com/questions/4975996/how-can-i-cross-browser-detect-input-fields-with-the-required-attribute-in-jqu

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