Sunday, June 5, 2011

Javascript autocomplete



Searching for "javascript autocomplete" yielded many results. I just wanted to link to one that I thought was just AMAZING. With minimal tweaks, it can be dropped into its own .js file for inclusion of your own files:

http://simpleandeasycodes.blogspot.com/2009/03/javascript-simple-autocomplete-textbox.html

UPDATE:
The source code for this project can be found here:http://www.codeproject.com/KB/scripting/jsactb.aspx. The original link appears to be identical code, except that the variable names have been changed from "actb*" to "saec*". Let's give credit where credit's due (and preserve a valid copyright notice at the time), huh?.


Step 1) Move the "var customarray = new Array (...);" out of the file. You'll be generating this yourself anyway.

Step 2) Create your own custom array of strings in a file.

Step 3) Tweak a few settings at the top of actb() to your liking (they are the ones under "Public Variables") such as delimiter, firstText, etc.

Step 4) Optional: Within the actb_checkkey() function, add one more case statement before default:

   case 27:                      // Escape key
      actb_mouse_on_list = 0;
      actb_removedisp();
      return false;
      break;





This way, if someone is typing something and does NOT want the autocomplete, they can hit the ESC key to close the autocomplete window (else they'll hit TAB or ENTER and the auto-suggested word will overwrite their entry).

Next, in your HTML, initialize the class by calling actb() on the field you want. It takes two arguments: the ID of the input field (a text or textarea), and the string array you created in Step 2. Start typing, and you'll have your own results.

One thing I like to use it for is to create a list of names found in an SQL database. Use PHP (or some other server-side language) to create a Javascript array of those names, and then allow the user search through those names with the autocomplete feature.

This script looks like it took the author quite a while to complete. Good job on an excellent piece of code!

No comments:

Post a Comment