Reputation: 88
I have a question about how to check when input text is changed? I use keydown
like this:
$('#query').keydown(function () {
console.log($(this).val());
});
But when the actual value is query
, the console will be log quer
. It always delay. I dont know why?
Upvotes: 0
Views: 89
Reputation: 1952
There's 3 ways to implement it.
The first way is using other event such as input
or propertychange
. Notice that propertychange
is supported only on IE and input
is supported on modern browsers.
$('#query').on('input perpertychange', function () {
console.log($(this).val());
});
The second way is putting console.log($(this).val());
in setTimeout
statement. You can get what you're typing. (The reason? I'm sorry, I really dont know why, just use it);
$('#query').keydown(function () {
var query = $(this);
setTimeout(function () {
console.log(query.val());
}, 0);
});
And the last one is using textchange
event (http://zurb.com/playground/jquery-text-change-custom-event). Like this:
$('#query').on('textchange', function () {
console.log($(this).val());
});
Upvotes: 3
Reputation: 16043
You can use .change()
$('#query').change(function () {
console.log($(this).val());
});
Upvotes: 0
Reputation: 388446
You can use the keyup event
$('#query').keyup(function () {
console.log($(this).val());
});
Upvotes: 2
Reputation: 382474
Don't use keydown
here but keyup
, so that the value of the input has changed when you receive the event.
See the MDN on the processing of key events.
Upvotes: 2