Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a control to readonly using jquery 1.6 .prop()

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?

like image 694
ajbeaven Avatar asked May 05 '11 01:05

ajbeaven


People also ask

What is prop method in jQuery?

jQuery prop() Method The prop() method sets or returns properties and values of the selected elements. When this method is used to return the property value, it returns the value of the FIRST matched element.

What is readonly 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.

What does Prop mean in JavaScript?

If you're already familiar with how arguments & functions work in JavaScript, understanding props is a piece of cake! In a nutshell, props are used to pass data from a parent component to a child component in React and they are the main mechanism for component communication.


2 Answers

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; 
like image 188
aroth Avatar answered Sep 25 '22 11:09

aroth


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.

like image 21
Code Maverick Avatar answered Sep 24 '22 11:09

Code Maverick