Irfan Mir
Irfan Mir

Reputation: 2175

Check input of value matches something on each keystroke

On each key up, or after the user types a letter I need to check if it is matching or matches one of two words. If what is typed is equal to or longer and not equal to one of the phrases, I run my custom fail() function. If it does match, then I run the pass function with an argument of 1 if the first word was matched and an argument of 2 if the second word was matches.

Right now, I am doing this with numerous if and else if statements that check if the value, using .val(), === the phrase. The if statements are inside the keyup function of the only input on the page.

There has to be a better way to do this than all these comparative statements. Possibly on key up check if the val is starting to match or does match any of the phrases in an array. If it does match any of the phrases, each an element, in an array then run pass() with the argument being the index of that matched word in the array+1. The moment it is equal to in length or longer and not equal to any of the phrases in the array, run the fail() function.

How would I do this?

Or if you have a better solution, please share.

Here are things that would cause a pass: 'help' or 'search'.

Things that would cause a fail: 'serach'(starting to match, but equal in length and doesn't match), lpeh (equal in length and doesn't match)', or 'bike'(equal in length and doesn't match), or 'dealt'(longer in length and doesn't match), or 'editor'(equal in length and doesn't match), or 'magazine'(longer in length and doesn't match).

Thank you for any and all help— I greatly appreciate it.

Upvotes: 0

Views: 226

Answers (1)

Dirk Stöcker
Dirk Stöcker

Reputation: 1638

Try this:

  1. Make an array of the allowed strings.
  2. Iterate over the array.
    • Return the array index (+1) when input and array entry is equal.
    • Exit if array_entry.indexOf(input) is 0 (i.e. the input is the beginning of array entry)
  3. Call fail() when you reach the end of the array.

Upvotes: 1

Related Questions