Is it possible to override an event for input fields when the user presses and holds the keyboard button?

There is a text field with id="char" , you need to somehow prohibit pressing and holding the key. But repeated characters can be in any quantity.

  • If you prohibit retention due to only repeated characters, then use the read at the time of the keyup. Ignoring keypress and keydown - Crystal

1 answer 1

 var value = ''; $('input').on('keypress', function(e) { if (value === e.key) { console.log('SAME'); e.preventDefault(); return; } value = e.key; }); $('input').on('keyup', function(e) { value = ''; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' /> 

We get a variable in which we write the key that we pressed. If the key is clamped (re-call keypress / keydown without calling keyup), then block. As it turned out, you better hang the event on keypress. he does not respond to special characters

"Any letters, numbers generate keypress. Control keys, such as Ctrl, Shift, F1, F2 ... - keypress does not generate." tyk

  • what window.preventAction ? - Grundy
  • @Grundy agree - corrected to e. Thank! - alexoander
  • and e.preventAction is that? - Grundy
  • @Grundy as far as I know, it is this flag that changes when e.preventDefault (). Those. when false, the default behavior is again active. And as it turned out, he is not needed = _ =. Corrected the answer. The Council took from here javascript.ru/forum/jquery/… - alexoander
  • Such a flag does not exist, this time, for your own link, see why they use the field in the window object. In your case, this is not necessary - Grundy