Setting up a control to read using jquery 1.6.prop ()

With the release of jQuery 1.6, the SO recommendation was to start with prop (), where you used attr ().

What happens when I want to make a readonly element?

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

None of them seem to do read-only control. Is a read-only item an exception to the rule?

+23
jquery readonly
May 05 '11 at 1:33
source share
2 answers

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

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

Although I really don't know why jQuery is required for this. This works just as well:

 document.getElementsByClassName("control")[0].readOnly = true; 
+38
May 05 '11 at 1:52
source share

Try the following:

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

I think of it this way:. attr () gets the default value in the html markup as well . prop () gets / sets the value dynamically. Take a 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 the following:

The difference between attributes and properties may be important in specific situations. Before jQuery 1.6, the .attr () method sometimes took property values ​​into account when getting some attributes that might lead to inconsistent behavior. In the form of jQuery 1.6, the .prop () method provides a way to explicitly retrieve property values, while .attr () retrieves attributes.

+8
May 05 '11 at 1:51 am
source share



All Articles