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" />
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
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With