Women in Technology

Hear us Roar



Article:
  Cooking with JavaScript & DHTML
Subject:   Small problem, with solutions and question
Date:   2004-12-23 12:34:42
From:   puck71
This is a great script, and I used it pretty much exactly as written (with the corrections for the TAB key and numpad entries)


The only problem I ran into is if I typed in a value longer than the value in the select element. For instance, I had a dropdown of all two digit numbers (01-99 sorted ascending) and if I typed "444" fast enough (before the timeout ran out) it would select "45" in the list, and if I typed "4444" it would select "40", and if I kept typing "4" before the timer ran out it would keep alternating between 40, 44, and 45. You can see this in action by just holding down the "4" key.


I found two solutions, depending on the desired result. If I wanted to just plain stop people from entering more than 2 digits, I replaced
typeAheadInfo.accumString += newChar;
with
if (typeAheadInfo.accumString.length < 2) { typeAheadInfo.accumString += newChar; }


This has some drawbacks - namely that if you mess up you have to wait until the timeout clears to start re-entering your date. The other solution I found is to keep the LAST two digits I entered, rather than the FIRST two. To do that, I left the above line alone, and inserted this right after it:
if (typeAheadInfo.accumString.length > 2) { typeAheadInfo.accumString = typeAheadInfo.accumString.substr((typeAheadInfo.accumString.length - 2), 2); }


Obviously the script is now no longer general, as my 2-character limit is hard-coded in. Is there a better way to solve the original problem I had?


Thanks,
John

Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • Small problem, with solutions and question
    2005-01-15 16:11:54  Danny Goodman | O'Reilly Author [View]

    While no easy generalizable solution comes to mind, you could possibly use the onload event to invoke a function that sets up an array (the pseudo-hash tables I describe in the book would be good for this) that associates each select element with a digit--the digit is calculated by iterating through all option values and finding the longest value. Then modify the typeAhead() function (as you've done), but substituting the matching hash table value for the maximum length of the active select element (hard-coded as 2 in your example).

    First thoughts on how I'd start to approach the problem.

    Good luck and thanks for reading.

    Danny