views:

135

answers:

2
​<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?

+1  A: 

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.

Trafalmadorian
well ok, but it's the add attribute that is really causing the problem.
fearofawhackplanet
I'd just do the adding the same way: $("#X").attr("readonly",true);
Trafalmadorian
also in this case, go by behavior, not by browser debuggers...sometimes they don't always track property changes like this correctly.
Trafalmadorian
Ok got it working after your edit. Thanks :)
fearofawhackplanet
+1  A: 

@Trafalmadorian - Note that .length isn't valid as the result doesn't return an array. You can do without the .length

BIGDeutsch
I'd reclassify this as a comment on my answer, this is not an answer in and of itself. Also, strings have length as well in JS, so it is perfectly valid.
Trafalmadorian
It is valid, a jQuery object is a wrapper for an array of DOM element references, so `.length` is a valid property: http://api.jquery.com/length/
Nick Craver
Nick's right as well (as always :P) but in this case we're not actually finding the length of a jQuery object match but the length of the attr return type, which potentially could be non-boolean if the value is "readonly." Although I'll be honest I haven't tested that.
Trafalmadorian
@Trafalmadorian - Doh, this should *really* be a comment, but the user doesn't have enough rep yet...I was reading this as a response to the question, not your answer, my fault.
Nick Craver
well it helped me as I didn't figure it out from the other answer alone. Thanks
fearofawhackplanet