Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set then read readonly attr on textbox

​<input id="test" type="text" value="text" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

alert(​$(':input:not([readonly])').length);​​​​​​​​​​​​​​​​​ // 1

$('#test').attr('readonly', 'readonly');

alert($(':input:not([readonly])').length); // 1

$('#test').removeAttr('readonly');​​​​​​​​​​

alert($(':input:not([readonly])').length); // 1

Further to the question here, I can't get the solution to work because it seems jQuery doesn't set the readonly attribute correctly (or at least consistently).

Note I get the same results with $('#test').attr('readonly', true);

I'm using Chrome, and the readonly attribute renders as readonly="". There is another post on here which suggests FireFox does the same.

I'm not much bothered about this in as much as it still stops the text box from being editable, but I can't then find a way to detect the readonly attribute.

I normally love jQuery but this is all a bit WTF.

Any ideas?

like image 919
fearofawhackplanet Avatar asked Sep 14 '10 14:09

fearofawhackplanet


People also ask

How do I set the Read Only attribute in jQuery?

Projects In JavaScript & JQuery To make a textarea and input type read only, use the attr() method .

How check textbox is readonly or not in jQuery?

Learning jQuery One of way is to make textbox readonly is to set "readonly" attribute to true. So use the same attribute "readonly" to find out whether textbox is readonly or not using jQuery. $(document). ready(function(){ $("#txtReadonly").

How can make text field readonly in HTML using jQuery?

How can you make a textbox readonly using JQuery? $('#TextBoxId'). attr('readonly', 'true');

How do I make a selection read only?

According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled .


1 Answers

I personally wouldn't use removeAttr()...I'd just set it to false with attr().

You could then just query the property normally:

if ($("#X").attr("readonly"))
{
    execute code
}

Also, you can keep using removeAttr(), and then just use the length as a way to detect the property:

if (!$("#X").attr("readonly").length)
{
    execute code
}

If you're worried about the selector, you should do the selector syntax as :not([readonly='readonly']) edit: I see that was already in the answer you cited.

like image 64
Trafalmadorian Avatar answered Oct 20 '22 22:10

Trafalmadorian