This doesn’t work:
In both Chrome and Firefox, the DOM produces either
required as the attribute (no value) or
required="" (empty value).
And it doesn’t matter that the value in this example is “true”. If you try “asdf” the same thing happens.
What’s odd is that I believe this used to work because this new code is part of a large project that’s been ongoing for several years.
The only thing I can think of is that my Chrome (v10) and Firefox (v4) are now both sufficiently advanced that they’re recognizing the required attribute as an HTML5 reserved keyword. I added the novalidate attribute, thinking that that might turn off any form-related HTML5-ness. No such luck.
To clarify, this only happens with JQuery. If I say this, it works:
The crux of the matter is this…
Why does using JQuery’s
attr() method not work when the regular
setAttribute() method does? Doesn’t the
attr() method call
setAttribute() at some point lower down?
That is what is so confusing. Chrome and Firefox are perfectly fine setting
required="true" if you use setAttribute().
It is indeed browser related. I checked in IE8 and it will apply whatever string value you set to the required attribute.
<input required> is the same as
<input required=""> and
Since IE8 doesn’t support html5, it’s just like setting a made-up attribute, so you could set
$("input").attr("derp", "derty") and it would assign it to the element.
My guess is that jquery uses the
required="" for folks who wish to use this in XHTML strict syntax, while still conforming to HTML5 standards.
You can use prop to achieve this:
Corresponding documentation: http://jquery.com/upgrade-guide/1.9/#attr-versus-prop-
document.getElementById("inputid").required = true;
document.getElementById("inputid").required = false;
depending on requirements.
I have read through .attr() and .prop() pages on the jQuery API, and there seems to be no support for the “required” attribute – but I am open to correction.
I use this fairly often and I haven’t noticed any problems with it.
Note: I have try this but I could NOT get it working:
Even though required is now a boolean attribute, simply adding the attribute name (without the value) does not appear to be too compatible with different versions of different browsers. Stick with my original example above and you should be fine.
For input required, it works much better if you remove the attribute vs. setting it to false