UnstableFractal
UnstableFractal

Reputation: 1422

How to check if value of input is changed?

I'm trying to check if input was changed or not. Problem is - if i'll use this code:

trigger.keyup(function() {
    current_input = getSearchString();
    is_changed = (current_input != previous_input);
    previous_input = current_input;
});

This logic will break when user will press, for example "Q", after a short delay "E" (input value will be "QE" already) and release "Q" key first. previous_input will be set to "QE". User releases "E" key and script compares equal strings. So, when input actually did change, for my script it is not. Any idea how to fix this or is there any different way to do this (not with html5 event 'input')?

Upvotes: 1

Views: 162

Answers (2)

techfoobar
techfoobar

Reputation: 66663

Depending on key events alone is not a reliable mechanism. For example: what is user pastes text from the clipboard, or if he drags and drops text into the textbox (yes, dnd works for textboxes).

To account for all possible channels, you can use the textchanged event. Details here: http://zurb.com/playground/jquery-text-change-custom-event

$('#selector').bind('textchange', function (e, prevText) {
    // do your stuff here
});

Upvotes: 0

Naftali
Naftali

Reputation: 146302

Use keydown instead of keyup, that way you are not reliant on whether or not the user releases the keys.

Upvotes: 6

Related Questions