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?

Answers


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


Need Your Help

How to get combobox not to accept user input in Excel-Vba?

excel vba controls excel-2007

Does anyone know what the properties are in the combobox that I can manipulate in order not to allow the user to key/type in any data?

Rails text_area size

ruby-on-rails

I have a text_area inside a fields_for, which is inside a form_for.