Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when input has a 'readonly' attribute

Tags:

jquery

I want to throw an alert when an input has a 'readonly' attribute. I have tried this:

  if($('input').attr('readonly') == 'readonly'){      alert("foo");   } 

I think that 'if' is not even the best way to do it.

like image 754
ziiweb Avatar asked Mar 24 '11 17:03

ziiweb


People also ask

How do you check if input field is read-only?

Use the readOnly property to check if an element is read-only, e.g. if (element. readOnly) {} . The readOnly property returns true when the element is read-only, otherwise false is returned.

Does readonly input get submitted?

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.

What is input readonly attribute specifies?

The readonly attribute is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

How check TextBox is readonly or not in jQuery?

So use the same attribute "readonly" to find out whether textbox is readonly or not using jQuery. $(document). ready(function(){ $("#txtReadonly"). attr('readonly', true); var isReadonly = $("#txtReadonly").


2 Answers

fastest way is to use the .is() jQuery function.

if ( $('input').is('[readonly]') ) { } 

using [readonly] as a selector simply checks if the attribute is defined on your element. if you want to check for a value, you can use something like this instead:

if ( $('input').is('[readonly="somevalue"]') ) { } 
like image 184
Richard Neil Ilagan Avatar answered Oct 03 '22 09:10

Richard Neil Ilagan


Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

if($('input').prop('readonly')){ } 

.prop() can also be used to set the property

$('input').prop('readonly',true);  $('input').prop('readonly',false); 
like image 30
keV Avatar answered Oct 03 '22 09:10

keV