Detect when input has a 'readonly' attribute

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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"]') ) { }

Solution 2 - Jquery

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);

Solution 3 - Jquery

what about javascript without jQuery ?

for any input that you can get with or without jQuery, just :

input.readOnly

note : mind camelCase

Solution 4 - Jquery

Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

$('input').each(function() {
	var readonly = $(this).attr("readonly");
	if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
		alert('this is a read only field');
	}
});

Solution 5 - Jquery

You can just use the attribute selector and then test the length:

$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0  // --> not ok

Solution 6 - Jquery

Try a simple way:

if($('input[readonly="readonly"]')){
   alert("foo");
}

Solution 7 - Jquery

try this:

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

if it is not there it will be undefined in js

Solution 8 - Jquery

In vanilla/pure javascript you can check as following -

var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
 alert("foo");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionziiwebView Question on Stackoverflow
Solution 1 - JqueryRichard Neil IlaganView Answer on Stackoverflow
Solution 2 - JquerykeVView Answer on Stackoverflow
Solution 3 - JqueryfadomireView Answer on Stackoverflow
Solution 4 - JquerypotenchView Answer on Stackoverflow
Solution 5 - JqueryJosiah RuddellView Answer on Stackoverflow
Solution 6 - JquerycachaitoView Answer on Stackoverflow
Solution 7 - JqueryNaftaliView Answer on Stackoverflow
Solution 8 - JqueryMusaView Answer on Stackoverflow