Useful Javascript for Select Box population

|

A couple of little useful Javascript helper functions for populating select boxes. If you've got a significant number of choices to present to the user, or a clear reason to categorise the choices presented (maybe providing the list of major towns to choose from restricted by a previous choice of county/state) dynamically populating/re-populating the select drop-down can make the user experience a lot better. There's also the added bonus that, for a list which could run to several hundreds of items, the download overhead of only bringing back those required, when required, by using a call to the server via the XMLHTTP object is significantly reduced as SELECT -> OPTION elements are quite verbose,

/*
Parameters:

controlID: The HTML ID of the element to populate
itemArray: An aray of arrays (of ) to use to populate the drop down
selectedIndex: [NOT USED] The selectedIndex value to use
*/
function populateDropDown(controlID, itemArray, selectedIndex)
{
var x = document.getElementById(controlID);
var item;
for (i = 0; i < itemArray.length; i++)
{
addOptionToDropDown(x, itemArray[i][0], itemArray[i][1]);
}
}

/*
Parameters:

dropDown: The selectbox DOM object to work on
itemValue: The value for the option.value attribute
itemText: The value for the option.text attribute

Notes:

Called by populateDropDown

*/
function addOptionToDropDown(dropDown, itemValue, itemText)
{
/*
Note: This code is Internet Explorer specific and will require changing if compatibility with other
browsers is needed (See: http://www.w3schools.com/htmldom/met_select_add.asp)
*/
var option = document.createElement('option');
option.id = dropDown.id + '_' + itemValue;
option.value = itemValue;
option.text = itemText;
dropDown.add(option);
}

About this Entry

This page contains a single entry by Robert Wray published on March 27, 2007 9:00 AM.

Using MSMQ (Message Queuing) from .net was the previous entry in this blog.

Simple construction of an XML Document in Javascript is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.04