Event on a disabled input

Pierre de LESPINAY picture Pierre de LESPINAY · Jun 23, 2010 · Viewed 240.3k times · Source

Apparently a disabled <input> is not handled by any event

Is there a way to work around this issue ?

<input type="text" disabled="disabled" name="test" value="test" />
$(':input').click(function () {
    $(this).removeAttr('disabled');
})

Here, I need to click on the input to enable it. But if I don't activate it, the input should not be posted.

Answer

Andy E picture Andy E · Jun 23, 2010

Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.

I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:

<div style="display:inline-block; position:relative;">
  <input type="text" disabled />
  <div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>​

jq:

$("div > div").click(function (evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});​

Example: http://jsfiddle.net/RXqAm/170/ (updated to use jQuery 1.7 with prop instead of attr).