Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - Setting an attribute named "required" and any value, with JQuery, doesn't work

This doesn't work:

$("#elementId").attr("required", "true");

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.

Thoughts?

Edit:

To clarify, this only happens with JQuery. If I say this, it works:

$("#elementId")[0].setAttribute("required", "true");

Is there a bug in JQuery? Any idea why this only happens with JQuery? Our development team likes all code to go through JQuery where possible. I can use the straight setAttribute JavaScript method, but would rather use a JQuery solution that works.

Edit 2:

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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use prop to achieve this:

$("#elementId").prop("required", true);

Corresponding documentation: http://jquery.com/upgrade-guide/1.9/#attr-versus-prop-


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...