Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the readonly attribute with JQuery or Javascript (BUT following the W3C standard!)

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?

like image 749
chelder Avatar asked Sep 09 '13 01:09

chelder


People also ask

How do I set the Read Only attribute in jQuery?

Use jQuery methods to add the readonly attribute to the form input field. jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of the first selected element.

How do you add a readonly attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.

How do I make a read only field editable in JavaScript?

A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

How do you set a readonly property in HTML?

The Boolean readonly attribute, when present, makes the element not mutable, meaning the user can not edit the control. If the readonly attribute is specified on an input element, because the user can not edit the input, the element does not participate in constraint validation.


1 Answers

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" />
like image 175
adeneo Avatar answered Oct 21 '22 06:10

adeneo