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.

HTML Form Builder
Ryan Campbell

Event Handlers on Disabled Inputs by Ryan Campbell

This entry was posted 5 years ago and was filed under Notebooks.
Comments are currently closed.

· 11 Comments! ·

  1. Justin · 5 years ago

    Disabled fields also don’t get sent back in the form submit, whereas readonly fields do.

  2. Douglas Clifton · 5 years ago

    Not surprising at all that disabled elements do not respond to events. Also, select elements have no readonly attribute.

  3. Ismael · 5 years ago

    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?

  4. Ryan Campbell · 5 years ago

    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.

  5. munkyboy · 5 years ago

    nice tip. I ran into this exact limitation today. Now I have a work-around. thanks!

  6. munkyboy · 5 years ago

    doh, I take it back… doesn’t work for checkboxes… :(

  7. Ismael · 5 years ago

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

  8. Tim Huegdon · 5 years ago

    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. :-)

  9. Colin D. Devroe · 5 years ago

    Excellent tip for those starting out in the wonderful world of HTML, period. Let alone the fact that events are retained.

  10. Duncan Beevers · 5 years ago

    Another possibility is to wrap the disabled element in a container and attach events to its container.

  11. Bruni · 3 years ago

    The problem with Readonly fields is that, if the field is empty and you press BACKSPACE, the browser goes back to the previous page.