AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 379


to see if the user selected one of the choices. In this case, all the clicks in the document will
be caught, but be careful: outside the simple example, this approach may be inappropriate.

window.onload = function ()
{
document.getElementById("suggestList").style.display = "none";
document.getElementById("country").onkeyup = function(e){checkKey(e,
this);};
document.onclick = checkClick;
/* kill default submit of a single field form */
document.requestForm.onsubmit = function(){return false;};
};

Every time a key is released in the suggestion field, checkKey()is invoked. This function
looks at the key and compares it to what is going on in the field and the suggestion list.

function checkKey(e, obj)
{
var country = document.getElementById("country");

/* get key pressed */
var code = (e && e.which)? e.which : window.event.keyCode;
/* if up or down move thru the suggestion list */
if (code == KEYDOWN || code == KEYUP)
{
var index = selectedIndex;
if (code == KEYDOWN)
index++;
else
index--;
/* find item in suggestion list being looked at if any */
var selectedItem = document.getElementById("resultlist" + index);
/* if something selected show it and set the field to the value */
if (selectedItem)
{
selectItem(selectedItem);
country.value = selectedItem.innerHTML;
}
}
else if (code == ENTER) /* clear suggestions upon enter key */
clearList();
else if (country == obj) /* otherwise go to network and get suggestions */
{
selectedIndex = -1;
getSuggestions(obj);
}
}

Reading the preceding function, you might note the usage of what looks visually like
constants (all uppercase identifiers) that represent the key codes we are interested in handling.
Free download pdf