Auto-complete Text Box

function showPopup(textBox, className){

// grab the textbox object
var textbox = document.getElementById(textBox);

// get the textboxes parent
var parent = textbox.parentNode;

// check to see if this popup is already on screen
var popup = document.getElementById(textBox + ‘_popup’);

if (!popup) {
// we don’t have a popup, lets create one

// create popup div
var popup = document.createElement(‘div’);
// give it a unique id
popup.id = textBox + ‘_popup’;

// attach css if passed in
popup.className = className || ‘popup’;

// set it’s left location
popup.style.left = textbox.offsetLeft;

// set it’s top location
popup.style.top = textbox.offsetHeight + textbox.offsetTop;

// make sure it’s absolute
popup.style.position = ‘absolute’;

// attach it to the text boxes parent node
parent.appendChild(popup);

}else{
popup.style.display = ‘block’;
}

// attach an event to remove the popup once it loses focus
document.onclick = function(){
if (popup){
popup.style.display = ‘none’;
delete popup;
}
};

// give it some content
popup.innerHTML += textbox.value + “
“;

}

.popupClass{
height: 150px;
width: 150px;
border: 1px solid black;
background: yellow;
overflow: auto;
}

This is a very simple script to lead you in the right direction towards making an auto-complete textbox, similar to Google Suggest (http://www.google.com/webhp?complete=1&hl=en). This script does not need any fancy framework to work.

Example:


function showPopup(textBox, className){

// grab the textbox object
var textbox = document.getElementById(textBox);

// get the textboxes parent
var parent = textbox.parentNode;

// check to see if this popup is already on screen
var popup = document.getElementById(textBox + '_popup');

if (!popup) {
// we don't have a popup, lets create one

// create popup div
var popup = document.createElement('div');
// give it a unique id
popup.id = textBox + '_popup';

// attach css if passed in
popup.className = className || 'popup';

// set it's left location
popup.style.left = textbox.offsetLeft;

// set it's top location
popup.style.top = textbox.offsetHeight + textbox.offsetTop;

// make sure it's absolute
popup.style.position = 'absolute';

// attach it to the text boxes parent node
parent.appendChild(popup);

}else{
popup.style.display = 'block';
}

// attach an event to remove the popup once it loses focus
document.onclick = function(){
if (popup){
popup.style.display = 'none';
delete popup;
}
};

// give it some content
popup.innerHTML += textbox.value + "
";

}

  1. No comments yet.

  1. No trackbacks yet.