Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onkeypress vs oninput how to get best of both worlds

So I'm using an input and need to get the keycodes so I tried using onkeypress. However, I also needed the updated value, which it doesn't actually have when keypress event is triggered.

So then I tried using oninput, however, while the updated value of an input is there, it doesn't register keyCode.

Right now I'm using both events, but was wondering if there was a catch-all event that both contains the keyCode and the updated input.

$("#test").on('keypress', () => {
  console.log("keypress value: ", event.target.value);
});
$("#test").on('input', () => {
  console.log("input value: ", event.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" />
like image 657
A. L Avatar asked Sep 12 '25 19:09

A. L


2 Answers

You can use keyup event. This will give you both keycode and updatedValue

$("#test").on('keyup', function(e) {
  console.log(e.keyCode, this.value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" />

When you type a key, following events occurs

  1. Key Down: This will register which key is being pressed down. If you want to prevent any key from being typed, this is where you block it.
  2. Key Press: This will register which key is being held. Its value is set on keyDown and erased on keyUp.
  3. Key Up: This is when you release the key and event chain is completed. This is the event that updates the value.
like image 158
Rajesh Avatar answered Sep 14 '25 08:09

Rajesh


Another important difference is that, when you try to upper or lower case, look at this different.

$("#testKeyPress").on('keypress', function () {
  $(this).val($(this).val().toUpperCase());
});

$("#testInput").on('input', function () {
  $(this).val($(this).val().toUpperCase());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
KEYPRESS <input id="testKeyPress"/> <br />
INPUT <input id="testInput" />
like image 43
Muhammet Can TONBUL Avatar answered Sep 14 '25 07:09

Muhammet Can TONBUL