How can I cross-browser detect input fields with the 'required' attribute in jQuery?
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?
It may be a bad workaround, but have your tried a multiple selector?
$(':input[required=""],:input[required]')
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>
with bootstrap 3, you can do:
$('input[required]')
.closest(".form-group")
.children("label")
.append(" <i class='fa fa-asterisk'></i>");
精彩评论