3

I want to add an attribute to a HTML element without a value using JQuery

<input id="r1" type="radio name="r1" value="1">

Add required

<input id="r1" type="radio name="r1" value="1" required>

How can this be done without the =""after the attribute?

6
  • 1
    don't worry about the ="", it's irrelevant just like the missing / Commented Jun 19, 2013 at 21:47
  • $('input').attr('required',''); Commented Jun 19, 2013 at 21:48
  • @KevinB I believe <DOCTYPE !html> would be required, tho. Commented Jun 19, 2013 at 21:48
  • why are there two id attributes Commented Jun 19, 2013 at 21:51
  • it's actually a boolean property and as such not required to have any value. You could add required='fred' and it would work the same. See :html5doctor.com/html5-forms-introduction-and-new-attributes Commented Jun 19, 2013 at 21:56

1 Answer 1

8

The standard practice would be to set the property to true

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

This actually results in markup that exactly reads

<input id="r1" required>

JSFiddle demo: http://jsfiddle.net/8SrED/

Sign up to request clarification or add additional context in comments.

4 Comments

Afaik setting a property won't set an attribute, especially any custom attribute.
Not sure if it matter but when I use that I get required="required" **** This was for $('#r1').attr() *****
@teemu, there are lots of prop/attr bindings: title, name, id, rel, draggable, disabled, required, href, src, className/class, and more, just to name some common ones.
setting the property using .prop sometimes will add an attribute and sometimes won't. It depends on the property and the browser, jQuery isn't doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.