Question

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?

Était-ce utile?

La solution

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());
});

Autres conseils

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.

You can use the keyup event

$('#query').keyup(function () {
    console.log($(this).val());
});

You can use .change()

$('#query').change(function () {
    console.log($(this).val());
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top