简体   繁体   中英

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.

  • But why? This behavior doesn't seem fair to me.
  • Any workaround?

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(){
    // ...
});

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM