14

The following code to add and remove the property readonly works (gotten from here):

$('#someid').prop('readonly', true);
$('#someid').removeProp('readonly');

But the W3C standard recommend to use the readonly attribute without a value (gotten from here):

We should use: <input type="text" readonly />

Instead: <input type="text" readonly="true or readonly or anything" />

As $('#someid').prop('readonly'); doesn't work. What is the code to do it properly?

Community
  • 1
  • 1
chelder
  • 3,819
  • 6
  • 56
  • 90
  • You're doing it right! – adeneo Sep 09 '13 at 01:45
  • I know, it just doesn't follow the W3C recommendation. Maybe is better to ignore it? :/ – chelder Sep 09 '13 at 01:48
  • 1
    By "w3c standard", you aren't referring to w3schools are you? – Dom Sep 09 '13 at 01:51
  • 3
    `w3schools` is in ***no way*** affliated with W3C (very misleading since the names are very similar). Use whatever material you see on w3schools with caution. IMO, never use w3schools. – Dom Sep 09 '13 at 02:03
  • I didn't know @Dom. Thanks for the clarification :) – chelder Sep 09 '13 at 02:14
  • Sure thing. From personal experience, using w3schools just lead to more questions rather than answers. In fact, that is the very reason you are here! w3schools contradicts itself! – Dom Sep 09 '13 at 02:16

1 Answers1

33

The proper way to do it is with :

$('#someid').prop('readonly', true);

or

$('#someid').prop('readonly', false);

and

$('#someid').removeProp('readonly');

works fine as well as these are all jQuery methods for the native:

document.getElementById('someid').readOnly = true;

which sets the readonly property appropriately, and if you inspect the element in the console you'll see that the readonly attribute is added without a value like it should be according to the W3C specifications.

readonly is a property, and prop() is the method for setting properties.

The specifications for HTML5 says:

readonly = "readonly" or "" (empty string) or empty
Specifies that element represents a control whose value is not meant to be edited.

this means the following is valid:

<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
adeneo
  • 312,895
  • 29
  • 395
  • 388