Gary
Gary

Reputation: 4211

Can't get .click() to work on a disabled textarea

I'm using jQuery. I have a disabled textarea: <textarea id="textarea" disabled="disabled"></textarea>. I want to make it so that when a user clicks on the textarea, it will do something, such as an alert box. So, I have $('#textarea').click(function() { alert('Test'); });.

However, this only works when the textarea is not disabled. So, how can I make the click event fire even when the textarea is disabled?

Upvotes: 3

Views: 5301

Answers (5)

adeneo
adeneo

Reputation: 318182

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.

You could do something like:

$(document).on('click', function(e) { 
    if (e.target.id === 'textarea') alert('works');
});​​​​

FIDDLE

But it's probably not cross-browser!

Another, and possible better way to do it, is to place another element on top of the disabled one and catch events on that element, something like :

var t = $("#textarea"),
    over = $('<div</div>');
    over.css({
        position: "absolute",
        top: t.position().top,
        left: t.position().left,
        width: t.outerWidth(),
        height: t.outerHeight(),
        zIndex: 1000,
        backgroundColor: "#fff",
        opacity: 0
    });

t.after(over);

$(over).on('click', function() { 
    alert('works');
});​

FIDDLE

Upvotes: 2

defau1t
defau1t

Reputation: 10619

You cant fire click event from disabled elements, though you can set the value e-g:

http://jsfiddle.net/j6tdn/28/

Upvotes: 0

mgraph
mgraph

Reputation: 15338

instead of disabled="disabled" why not use readonly, readyonly is alomst same as disabled and the click event will works

Upvotes: 14

Charlie Rudenst&#229;l
Charlie Rudenst&#229;l

Reputation: 4338

Instead of disabling it, you could either try simulating the disabled behaviour with CSS and continue receiving mouse events from it.

Or see this answer Event on a disabled input where Andy E shows how you can place an invisible element (an overlay) on top of the input for receiving those mouse events when the input is disabled.

He removes the overlay and enables the input when it is clicked, but you could change the behavior to anything you'd like.

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Disabled elements don't fire click events. That's part of them being disabled.

Upvotes: 1

Related Questions