JavaScript autocomplete

This post shows simple autocomplete JavaScript library. For every text input, functions prepares URL and displays popup with answers returned from server. Popup is shown below input field with exact width as input field.

Please try to input text in input fields. Autocomplete popup should work in IE, FF, Opera, Safari and Google Chrome. Example uses PHP to generate random autocomplete answers.


REDIPS.autocomplete uses AJAX for sending queries to the server. When last character is typed in the input field, query will be sent to server but DIV container will still be hidden. In a moment when reply arrives from the server, REDIPS.autocomplete will prepare SELECT multiple HTML code and popup will appear below input field. Width of the popup will be the same as is width of input field. Here is redips-autocomplete.php used for this demo:

<?php
// input parameters sent from sendURL method
$query = $_REQUEST['query']; // query
$fname = $_REQUEST['fname']; // field name
// random loop
for ($i = 0; $i < rand(6, 9); $i++) {
	print "<option>$fname$query$i$i$i</option>"; 
}
?>

Install instructions:

  1. Include redips-autocomplete-min.js file (3.9KB) in HTML page.
  2. Call REDIPS.autocomplete.init() after page is loaded (simply call from onload event handler).
  3. Add event handlers onkeydown and onblur to input filed you want to have autocomplete option (don’t forget to set name to the input field):
    • onkeydown=”REDIPS.autocomplete.keydown(this, event)”
    • onblur=”REDIPS.autocomplete.hide()”
  4. Add server logic inside redips-autocomplete.php for typed text (URL for generated options can be changed with REDIPS.autocomplete.url parameter).
  5. Answers should be in format <option></option>

Here is code snippet from REDIPS.autocomplete library. Complete redips3.tar.gz package can be download from icon below post title.

/**
 * sendURL() is a private method called on every text change in input field.
 * After every character input, timer is restarted (default timeout is set to 500ms).
 * When timer finishes, sendURL will send URL to query reply from the server.
 * Reply from server will be displayed to the popup below input field.
 * Timer value can be modified with REDIPS.autocomplete.delay property.
 * @see <a href="#delay">REDIPS.autocomplete.delay</a>
 * @private
 * @memberOf REDIPS.autocomplete#
 */
sendURL = function () {
	// cancel previous call if there is any
	if (timer !== null) {
		clearTimeout(timer);
	}
	// set new popup call
	timer = setTimeout(function () {
		// define oTop, oLeft and box variables  
		var oTop = 0,
			oLeft = 0,  
			box = oInput;
		// if user deletes content from input box, then hide popup and return
		if (oInput.value.length === 0) {
			hide();
			return;
		}
		// find input field position
		do {
			oLeft += box.offsetLeft;
			oTop += box.offsetTop;
			box = box.offsetParent;
		}
		while (box);
		// set top and left position of DIV element regarding to input element
		div.style.top = (oTop + oInput.offsetHeight) + 'px';
		div.style.left = oLeft + 'px';
		// set width to the DIV element the same as width of the input field
		div.style.width = oInput.offsetWidth + 'px';
		// open asynchronus request
		request.open('GET', REDIPS.autocomplete.url + oInput.value + '&fname=' + oInput.name, true);
		// the onreadystatechange event is triggered every time the readyState changes
		request.onreadystatechange = function () {
			var output;
			// request is finished and response is ready
			if (request.readyState === 4) {
				if (request.status === 200) {
					output = '<select multiple ondblclick="REDIPS.autocomplete.selected(this)" ' +
							'onkeydown = "REDIPS.autocomplete.keydown(this, event)" ' +
							'onblur = "REDIPS.autocomplete.hide()" ' +
							'onclick = "window.event.cancelBubble = true" ' +
							'style = "width:100%; height:100%">';
					output = output + request.responseText;
					div.innerHTML = output + '</select>';
					show();
				}
				// if request status is not OK then display error
				else {
					div.innerHTML = 'Error: [' + request.status + '] ' + request.statusText;
				}
		    }
		};
		// send request
		request.send(null);
	}, REDIPS.autocomplete.delay);
};


7 thoughts on “JavaScript autocomplete

  1. Very nice working script, I have implemented it on my website for my search page where it will look at what you typed and compare it to users,items,pets, etc. There is just one question I have, is there any way that you can make it so if there are less than 5 results for it to show, it shrinks the autocomplete box to fix just how many there are? Even if there are 0, it just won’t show up, but if there were let’s say 3 results that it found like what you typed in, the box shrinks to just fit those three.

  2. @Jason – I think is possible, but on the other hand it may have side effect. For example, in case when result is not found user may think that something is wrong and autocomplete mechanism is not working. So, when an empty popup is shown this is also a sign that none of data is found on the server (user should change typed text).

    Anyway, with some basic JS skills, this code can be modified to support your request. Hope this would not be a problem for your case.

Leave a Comment