Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on disabled button programatically not working

$(function () {
    $('#save').click(function() {
        $('#save').attr('disabled', 'disabled');
        console.log($(document.activeElement).attr('id'));
    });
    $('#test').focus();
    console.log($(document.activeElement).attr('id'));
});
button:focus {
  outline: 1px dotted #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<body id="body">
  <button id="discard" disabled="disabled">Discard</button>
  <button id="save">Save</button>
</body>

I have a Discard Changes button, and when clicked, the user sees a confirmation dialog that says "Are you sure you want to discard your changes?". When they click OK, we close the dialog and want to put focus back on the Discard Changes button, but we've disabled it now because there are no changes to discard. When I check the document.activeElement value, it's not the disabled button, it's the body element. However, when a user clicks the Save button, since they're physically setting focus on the element, it gets the focus so even after it's disabled, it has focus. For some reason in the snippet I'm not seeing my focus style set on the disabled Save button even though in my app I do see it.

Is it possible to set focus on a disabled button using jQuery? If not, why not? If so, what am I doing wrong?

like image 738
elemjay19 Avatar asked Oct 23 '25 01:10

elemjay19


1 Answers

No, the button cannot receive focus because it is disabled. According to the W3.org specification (HTML5 version) disabled form controls must prevent click events and other interaction.

What you would need to do is enable the control at some point and assign focus that way. Another suggestion would be to leave the button enabled and implement some form of detection to determine whether or not to respond to the discard button's click event.

Also, (and I'm taking a guess here) the save button likely shows as active because it was active before it was disabled. Although the browsers need to prevent access to a disabled item though interaction, removing the focus (or document.activeElement in this case) may not be an implementation requirement of the specification.

like image 138
Crackertastic Avatar answered Oct 25 '25 15:10

Crackertastic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!