Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .live('click') fires even on disabled buttons

I'm using the latest versions (jQuery 1.7.1 and jQuery UI 1.8.16) of all libraries, but buttons that I've binded a .live('click') event to still fire even when the button is disabled. When I bind a regular .click() event to it, it does not fire.

Any suggestions? I'm thinking either I'm using .live() improperly or this is a bug in jQuery UI.

Here's a JSFiddle to demonstrate. http://jsfiddle.net/Kb66j/1/

Thanks! Alex

like image 785
jalexsmith Avatar asked Jan 18 '12 17:01

jalexsmith


People also ask

Does click event fire on disabled button?

If an element is disabled, it looks as "onclick" events are not fired. The sample of the code: <input id="subm_tc" class="btn btn-primary" type="submit" disabled="" value="Log in" name="Submit"> $("#subm_tc").

How does jQuery live work?

jQuery live() Method The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).


2 Answers

That is because live takes advantage of event bubbling. When you click on a disabled button the event is still bubbled so the live triggers the event and all the click event handlers are executed. You can check the enabled state of the button inside the handler before you execute anything. Try this

$("#the_button").button({
        icons: {
            primary: "ui-icon-disk"
        },
    disabled: true
}).live('click',function () {
    if($(this).is(':enabled')){
         alert('clicked');
    }
});

Working Demo

Also as stated by others live is deprecated from 1.7+ version so you might try and use on but this issue will still be there and you have to handle it the way I described above.

like image 149
ShankarSangoli Avatar answered Sep 24 '22 16:09

ShankarSangoli


As of version 1.7, .live() has been deprecated.

"As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers."

Also, as of version 1.7, .on() is preferred over .bind()

"As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document."

like image 28
Sparky Avatar answered Sep 24 '22 16:09

Sparky