domi
domi

Reputation: 521

Disabled button still fires using ".click()"

It seems disabled button "onclick" function is still fired when triggering it programmaticaly, eg:

<div>
   <input type="button" onclick="save()" id="saveButton"    value="save"  disabled="disabled" />
   <input type="button" onclick="byPassDisabled()" value="bypass disabled button"/>
<div id="counter">0</div>

function save(){
    var count = parseInt($('#counter').html());
    $('#counter').html(++count);
}
function byPassDisabled(){
     $('#saveButton').click();   
}

see http://jsfiddle.net/WzEvs/363/

In my situation, keyboards shortcuts are bound to functions triggering the ".click()" on buttons. I'll find it very annoying to have to disable the shorcuts or check if the button is disabled myself. I'd prefer a general solution fixing this problem.

Upvotes: 15

Views: 32299

Answers (4)

rtmalone
rtmalone

Reputation: 308

For future use...the OP code works because jQuery will still call it's own handlers even if the DOM element is disabled. If one were to use vanilla javascript, the disabled attribute would be honored.

const element = document.getElementById('saveButton');
element.click() //this would not work

Upvotes: 5

Vijay
Vijay

Reputation: 3023

You can programmatically trigger click on a disabled button.

There are ways to find if the event is a click on button by user or it has been trigger programmatically. http://jsfiddle.net/WzEvs/373/

$(function () {
    $("#saveButton").on('click', function (e) {
        if (!e.isTrigger) {
            var count = parseInt($('#counter').html());
            $('#counter').html(++count);
        }
    });
    $("#bypassButton").on('click', function (e) {
        $("#saveButton").click();
    });
});

e.isTrigger is true if you call the click() programmatically. Basically you are triggering the click event manually in code.

Upvotes: 2

Spokey
Spokey

Reputation: 10994

The attribute only disables user interaction, the button is still usable programmatically.

So yeah, you gotta check

function byPassDisabled(){
    $('#saveButton:enabled').click();   
}

Alternatively don't use inline handlers.

$(document).on('click', '#saveButton:enabled', function(){
    // ...
});

Upvotes: 28

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

You can trigger click still although made it disable .As Spokey said it just shows the user-interaction(the usability still persists that can be turned on programmatically) . off or unbind the click will solve this issue.

Thanks

Upvotes: 0

Related Questions