I have a survey on a website, and there seems to be some issues with the users hitting enter (I don\'t know why) and accidentally submitting the survey (form) without clicki
If you don't have a in your form, then just add the following to your
:
Or with jQuery:
$(document).on("keydown", "form", function(event) {
return event.key != "Enter";
});
This will cause that every key press inside the form will be checked on the key
. If it is not Enter
, then it will return true
and anything continue as usual. If it is Enter
, then it will return false
and anything will stop immediately, so the form won't be submitted.
The keydown event is preferred over keyup as the keyup
is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter
is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).
Note that $(window)
as suggested in some other answers instead of $(document)
doesn't work for keydown
/keyup
in IE<=8, so that's not a good choice if you're like to cover those poor users as well.
If you have a in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a
.
To reduce boilerplate, this is better to be done with jQuery:
$(document).on("keydown", ":input:not(textarea)", function(event) {
return event.key != "Enter";
});
If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.
$(document).on("keydown", ":input:not(textarea)", function(event) {
if (event.key == "Enter") {
event.preventDefault();
}
});
If you'd like to allow enter key on submit buttons too, then you can always refine the selector as below.
$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
// ...
});
Note that input[type=text]
as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.