I suggest using keypress
instead of keyDown
so it does not limit the activation of the ctrl keys, such as: Backspace
, Delete
, Etc. Although I lean towards the use of jQuery as well, I show in its place and for illustrative purposes the use of addEventListener () to handle the onKeyPress
event associated with <input>
, as well as the use of event.preventDefault () , to prevent the normal flow of <input>
in case of not typing the required values.
Example:
document.getElementById("name").addEventListener("keypress", doNotSubmitFormOnEnterPress);
function doNotSubmitFormOnEnterPress(event) {
if(";_".indexOf(event.key) == -1){ // colocar la cadena de caracteres permitidos
event.preventDefault();
};
};
<input id="name">