JavaScript autocomplete

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

Try demo to see how autocomplete works.

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

<?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>"; 
}
?>

Instructions how to use autocomplete:

  1. Include redips-autocomplete-min.js in HTML page
  2. Call REDIPS.autocomplete.init() after page is loaded
  3. Add event handlers onkeydown and onblur to input fields
    • onkeydown=”REDIPS.autocomplete.keydown(this, event)”
    • onblur=”REDIPS.autocomplete.hide()”
    • don’t forget to set input filed name attribute (needed for server side)
  4. Add server logic inside redips-autocomplete.php for typed text
    • server side logic should return answers in <option></option> format
    • URL can be changed with REDIPS.autocomplete.url

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

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
		let 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
		xhr.open('GET', REDIPS.autocomplete.url + oInput.value + '&fname=' + oInput.name, true);
		// set callback handler
		xhr.onreadystatechange = function () {
			let output;
			// if operation is completed (readyState === 4)
			if (xhr.readyState === XMLHttpRequest.DONE) {
				// if the HTTP status is OK
				if (xhr.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 + xhr.responseText;
					div.innerHTML = output + '</select>';
					show();
				}
				// if request status is not OK then display error in dialog
				else {
					div.innerHTML = 'Error: [' + xhr.status + '] ' + xhr.statusText;
				}
			}
		};
		// in a good manners, set 'X-Requested-With' HTTP header
		xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		// send request
		xhr.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