I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
- Input field always maintains the focus.
- Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
- Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is – what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said – how do you know when the person has stopped “typing.” Unless you use some sort of timing mechanism (which is more trouble than it’s worth), you don’t. My suggestion would be to utilize a “div” within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So…how to do this…
Let’s assuming your input field has an id of “myField.” If you are using jQuery (which is in your tags), you would do something like this.
Alternatively, if you don’t want to use the keypresses variable, you can also use..