Eddy
Eddy

Reputation: 88

Check input when text is changed

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

Answers (4)

ducdhm
ducdhm

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

gprasant
gprasant

Reputation: 16043

You can use .change()

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

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

You can use the keyup event

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

Upvotes: 2

Denys Séguret
Denys Séguret

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

Related Questions