1

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')?

3
  • 1
    Would keydown help here? Commented Apr 26, 2013 at 13:20
  • 1
    onchange tells you when it changed. Commented Apr 26, 2013 at 13:21
  • 2
    onchange only fires when you lose focus Commented Apr 26, 2013 at 13:22

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, i've got confused because this part is combined with other logic in my script. Yeah, that'll completely solve my problem, thanks :)
No problem @smsteel Happy to help! ^_^
0

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

10 Comments

Hmmmm then you can just listen to both change and keydown, no real need to add a plugin for it...
@Neal - Wrong! change won't fire for text inputs unless you press enter or lose focus.
Right! Here you go: jsfiddle.net/maniator/7skY7 :-) it shows what was pasted into the input :-) All without an extra plugin (Here is the reason for the timeout: stackoverflow.com/questions/2055224/…)
@Neal - paste solves it to a large extent, yes (wont work in opera & older versions of safari - but will work on any decent new browser). Still it won't work if the user drags and drops text into the input.
I think the real comment here should be about bind() being used. jQuery team suggests we use .on for this in recent versions (actually for a while now)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.