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?

ojhawkins
  • 3,200
  • 15
  • 50
  • 67

1 Answers1

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/

compid
  • 1,313
  • 9
  • 15
  • 1
    Afaik setting a property won't set an attribute, especially any custom attribute. – Teemu Jun 19 '13 at 21:52
  • Not sure if it matter but when I use that I get `required="required"` **** This was for `$('#r1').attr()` ***** – ojhawkins Jun 19 '13 at 21:52
  • @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. – dandavis Jun 19 '13 at 22:02
  • 3
    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. – Kevin B Jun 19 '13 at 22:05