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.
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.
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.
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).
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").
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"]') ) { }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With