28

With the release of jQuery 1.6, the recommendation on SO has been to generally start using prop() where you used to use attr().

What happens when I want make an element readonly?

$('.control').prop('readonly', 'readonly');
$('.control').prop('readonly', true);

Neither of these seem to make the control readonly. Is making an element readonly the exception to the rule?

ajbeaven
  • 9,265
  • 13
  • 76
  • 121
  • 1
    You shouldn't be using `prop()` wherever you used `attr()`, just when you want to access a property or a HTML attribute (I think). – alex May 05 '11 at 01:41
  • @alex You SHOULD be using `prop()` in many cases, as `attr()` can refer to the original markup attribute value, which may be empty and / or be different to the current value of `prop()` (the property). – Chris Feb 19 '13 at 10:44
  • 2
    I think he's referring to the comment I made: "start using prop() where you used to use attr()". This is not entirely true - only use it when it's necessary (ie. accessing a property). – ajbeaven Feb 19 '13 at 10:56

2 Answers2

50

The problem is that the property name is case-sensitive. Try:

$('.control').prop('readOnly', true);

Though really I don't know why this requires jQuery. This works just as well:

document.getElementsByClassName("control")[0].readOnly = true;
aroth
  • 54,026
  • 20
  • 135
  • 176
  • 2
    I wouldn't use the 2nd example you've given, on readability alone. This is probably too obvious to mention, but you didn't seem to take that into consideration in promoting it – PandaWood Mar 22 '12 at 00:26
  • 3
    That depends how you measure readability. The semantics of `$()` and `prop()` are not exactly obvious to people without experience in JavaScript and jQuery. On the other hand `getElementsByClassName()` pretty much tells you exactly what it does. There's something to be said in favor of self-documenting code. – aroth Mar 22 '12 at 04:54
  • 2
    Do you see how much longer the second statement is? 25 characters. We don't have time for that. – Scott Pelak Oct 02 '14 at 19:25
12

Try this:

$(".control").prop({ readOnly: true });

I think of it like this: .attr() gets the default value in the html markup while .prop() gets/sets the value dynamically. Look at the following:

<input id="someInput" readonly="readOnly" />

$(".control").attr("readOnly") // would yield "readOnly"
$(".control").prop("readOnly") // would yield true
$(".control").is(":readOnly")  // would yield true

The api documentation says this:

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() only retrieves attributes.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114