We ran into an interesting situation this week. We have input fields that should never get focus, but they need to be able to respond to events, such as onclick
, onmousedown
, and onmouseup
. So, in order to take care of the focus part, we set the field to disabled.
As expected, the user can no longer click in the field. Surprisingly, this broke all of the events we had previously attached to the field. So a mouseclick on top of the field no longer triggered any JavaScript event handler related to that field. But it turns out there is an easy fix: just use readonly instead of disabled, and you’re good to go.
Disabled fields also don’t get sent back in the form submit, whereas readonly fields do.
Not surprising at all that disabled elements do not respond to events. Also, select elements have no readonly attribute.
or you could blur() the elements on click so they dont get selected, o wrap the field in something and apply the events to that container element…What’s the point of applying handlers to disabled elements anyway?
Our situation was probably pretty unique in relation to most. Our particluar form doesn’t submit anywhere, requires select elements to be active, and requires textarea/text to be disabled but still clickable. Weird, I know. You will see why soon enough though.
nice tip. I ran into this exact limitation today. Now I have a work-around. thanks!
doh, I take it back… doesn’t work for checkboxes… :(
In any case, I guess “readonly” makes more semantic sense to what you were trying to achieve: a field that your can read and perform certain actions on but not modify.
Still trying to figure out what kind of app it is. Come on! Just one hint!;-)
Woah - I haven’t used readonly for about 5 years. Back then it didn’t work in all the browsers.
I’m guessing it does now then, huh?
Lesson learned. :-)
Excellent tip for those starting out in the wonderful world of HTML, period. Let alone the fact that events are retained.
Another possibility is to wrap the disabled element in a container and attach events to its container.
The problem with Readonly fields is that, if the field is empty and you press BACKSPACE, the browser goes back to the previous page.