How can I crossbrowser enter input fields with a required attribute in jQuery?

I ran into a small validation problem with the Boolean required attribute in the form fields.

I mark 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.

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

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

What am I doing wrong here? The last thing I checked, the input attribute was just required , and neither required="required" nor required="true" .

Is there a better way to detect all the required fields using javascript / jQuery?

+4
source share
3 answers

This might be a bad workaround, but have you tried multiple selectors?

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

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
source

using bootstrap 3, you can do:

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

Source: https://habr.com/ru/post/1339440/


All Articles