Auto-suggest v3

Basic auto-suggest functionality using only javascript
HTML • JavaScript

Paste this code into an external JavaScript file named: autoComplete.js

var aMail = new Array("albert@mail.com","steve@mail.com","beth@mail.com","harry@mail.com","barry@mail.com", "allen@mail.com", "susan@mail.com", "hal@mail.com");
aMail.sort();

function Complete(obj, evt) {
	 if ((!obj) || (!evt) || (aMail.length == 0)) {
 	 	return;
  }

  if (obj.value.length == 0) {
  		return;
  }

  var elm = (obj.setSelectionRange) ? evt.which : evt.keyCode;

  if ((elm < 32) || (elm >= 33 && elm <= 46) || (elm >= 112 && elm <= 123)) {
  		return;
  }

  var txt = obj.value.replace(/;/gi, ",");
  elm = txt.split(",");
  txt = elm.pop();
  txt = txt.replace(/^\s*/, "");

  if (txt.length == 0) {
  		return;
  }

  if (obj.createTextRange) {
   	var rng = document.selection.createRange();
  		if (rng.parentElement() == obj) {
   			elm = rng.text;
  	 		var ini = obj.value.lastIndexOf(elm);
  		}
  } else if (obj.setSelectionRange) {
  		var ini = obj.selectionStart;
  }

  for (var i = 0; i < aMail.length; i++) {
   	elm = aMail[i].toString();
  		if (elm.toLowerCase().indexOf(txt.toLowerCase()) == 0) {
   			obj.value += elm.substring(txt.length, elm.length);
  	 		break;
  		}
  }

  if (obj.createTextRange) {
  		rng = obj.createTextRange();
  		rng.moveStart("character", ini);
  		rng.moveEnd("character", obj.value.length);
  		rng.select();
  } else if (obj.setSelectionRange) {
  		obj.setSelectionRange(ini, obj.value.length);
  }
}

Paste this code into the HEAD section of your HTML document. You may need to change the path of the file.

<script type="text/javascript" src="autoComplete.js"></script>

Paste this code into the BODY section of your HTML document

<form name="anyForm" style="text-align: center;">
  <small>(Begin entering one of the names below)<br>
  <em>Albert, Allen, Barry, Beth, Hal, Harry, Steve, Susan</em></small><br><br>
  <strong>Send e-mail to:</strong> 
  <input type="text" name="anyName" onKeyUp="Complete(this, event)">
</form>

Written by Frank Joseph Brefere III

Posted by fbrefere001 on Tuesday September 12, 2006