AutoComplete Users Input in Form

[Total: 0    Average: 0/5]

This javascript has 5 internal strings set up that it is looking for the user to enter. It will complete the input based upon the first character entered. If there are more than 1 match, it will use the first found entry in the array. When it finds th

Body Code:

Values to search from:<BR>
<script type=text/javascript>
var _values = ["one","two","three","four","five","fireman","firstplace","first place","oneton"]
for (i in _values)
  document.write(" "+_values[i]);
document.write("<BR>");
var _lastValue='';
function replaceText(_v) {
  var _count = 0; // number of different strings pattern was found in.
  var _index = -1; // index in the array of the item found.
  var _str = ""; // the new value in the text-box
  var _tempArray = new Array();
  if (document.f1.t1.value) _str = document.f1.t1.value;
  if (_lastValue == _str) return; // nothing need be done
  if (_lastValue.length>_str.length) {_lastValue=_str;return;} // deleted a char
  for (i in _values) {
    // is this new value in one of the items in the array?
	// (it must start at the begining of the item'string)
    if (_values[i].indexOf(_str) == 0) {
	  _tempArray[_tempArray.length] = _values[i];
	  _count++;
	  _index = i;
	  }
  }
  if (_index >= 0 && _index < _values.length && _count>0) {
    if (_count == 1) {
	  _str = _values[_index];
	} else {
	  _str = _values[_index].substring(0,lenToUse(_tempArray));
	}
    document.f1.t1.value=_str;
    _lastValue = _str;
  }
}
// this returns an integer that represents the length of
// the given strings in _index where all parameters are
// equal up to
// 1 -> first char's match only.
// 0 -> no match.
function lenToUse(_list) {
  var mismatchFound = false;
  var _return = 0;
  var _shortestLength = 99;
  for (i=0;i<_list.length;i++) {
    // find out the shortest string's length
	if (_list[i].length < _shortestLength)
	  _shortestLength = _list[i].length;
  }
  for (i=0;i<_shortestLength;i++) {
    // see if each charater in all _list's strings are equal intil their are
	// not - then that is the return value.
	_matchStr = _list[0].substring(i,i+1);
	for (j=1;j<_list.length;j++) {
	  if (_list[j].substring(i,i+1) != _matchStr) {
		if (!mismatchFound) // only track upto the first time a mismatch is found.
		  _return = i-1; // last round was succesful.
	    mismatchFound = true;
	  }
	}
    if (!mismatchFound) {
      _return = i;
    }
  }
  return (_return+1); // this makes the return value start at 1 for first position
}

function compute(e) {
  setTimeout('replaceText()',30); // 30 msecs later...
}
</script>
<form name="f1">
<input name="t1" type="text" onKeyPress="compute()" value="">
</form>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *