tirenweb
tirenweb

Reputation: 31749

Detect when input has a 'readonly' attribute

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.

Upvotes: 77

Views: 128123

Answers (8)

Musa
Musa

Reputation: 4024

In vanilla/pure javascript you can check as following -

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

Upvotes: 1

fadomire
fadomire

Reputation: 1975

what about javascript without jQuery ?

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

input.readOnly

note : mind camelCase

Upvotes: 12

keV
keV

Reputation: 349

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

Upvotes: 33

cachaito
cachaito

Reputation: 343

Try a simple way:

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

Upvotes: 3

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

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

Upvotes: 166

potench
potench

Reputation: 3842

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

Upvotes: 5

Naftali
Naftali

Reputation: 146350

try this:

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

if it is not there it will be undefined in js

Upvotes: 1

Josiah Ruddell
Josiah Ruddell

Reputation: 29841

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

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

Upvotes: 3

Related Questions