0

I am running into inconsistent behavior between Chrome and Internet Explorer, where IE functions and Chrome doesn't. I am trying to make a form accept the Enter key to be submitted. This is the Javascript for it:

$("#formElementId").on("keyup", function (e) {
    if (e.keyCode == 13 || e.which == 13) {
        if (e.target.id == "excludedElementId")
            e.stopPropagation();
        else
            document.getElementById("submitButtonId").click();
    }
});

The reason it doesn't work in Chrome is because a form element doesn't accept key input. This can be fixed by assigning the form element a tabindex value, which will allow it to be focusable. This is the recommended solution in this SO post.

This doesn't seem like the right solution. When focused, a soft border displays around the element, which I will have to hide. Also, its tabindex it will precede the actual form input controls in tabindex, which is not desired.

Is there a better way to handle the enter key for Chrome? And lastly, why does IE accept key input at the form level?

user3750325
  • 1,502
  • 1
  • 18
  • 37
  • typically, if you have a `type="submit"` in your form, then any field-focus will submit the form upon . is there a specific reason you want to wait until someone manually moves outside of the field (with their mouse) and clicks, then takes their hand off the mouse to press ? – Napoli Mar 05 '19 at 20:52
  • Good question. I was assuming focus anywhere in the form would submit. Is it typical practice that enter only submits form if the key input happens in a field? There are a lot of dropdown and datepicker controls on this page that people will select with the mouse, and then click outside of it to collapse the popup. I'd like to still handle enter after they click outside of it. – user3750325 Mar 05 '19 at 20:58
  • that's just it, why would you take your hand off the mouse to press enter; wouldn't you just "click" a date, then click "submit"? All controls should be accessible anyway, meaning; after you pick a custom drop-down item, slider value, etc.. the control should still have focus; you should still be able to just hit – Napoli Mar 05 '19 at 21:44

1 Answers1

1

Set tabindex="-1" to make it focusable but not part of tab order. See MDN for documentation on this behaviour.

Use a css style for the form with the :focus css selector to control the styling when the form has focus (and remove its border or outline or whatever it has when focused).

Brandon
  • 38,310
  • 8
  • 82
  • 87