jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
Realizing that this is a rather old post, I'll provide an answer anyway as I was struggling with the same problem.
You should use the "input"
event instead, and register with the .on
method. This is fast - without the lag of keyup
and solves the missing latest keypress problem you describe.
$('#dSuggest').on("input", function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
Demo here
This is because keypress
events are fired before the new character is added to the value
of the element (so the first keypress
event is fired before the first character is added, while the value
is still empty). You should use keyup
instead, which is fired after the character has been added.
Note that, if your element #dSuggest
is the same as input:text[name=dSuggest]
you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id
of another element is not a good idea).
$('#dSuggest').keypress(function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
Use .keyup
instead of keypress.
Also use $(this).val()
or just this.value
to access the current input value.
DEMO here
Info about .keypress
from jQuery docs,
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.
You have to interrupt the execution thread to allow the input to update.
$(document).ready(function(event) {
$("#dSuggest").keypress(function() {
//Interrupt the execution thread to allow input to update
setTimeout(function() {
var dInput = $('input:text[name=dSuggest]').val();
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
}, 0);
});
});
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