Creating Dynamic Combo-boxes with Javascript

How to use Javascript to create Dynamic Drop-Down Lists

© Mark Alexander Bain

Dec 18, 2008
A Dynamic Drop-Down Box, Mark Alexander Bain
Dynamic drop-down lists can improve the user experience on any web site - and the programmer can make them dynamic by using Javascript

Drop-down list boxes (or combo-boxes) are very useful objects on a web site - they give the user the opportunity to select an option from a list; and they're simple to implement - the programmer uses the select tag to define the drop-down list box and option tags to add items. However, the contents of a drop-down list box are static. Javascript is required if the drop-down list boxes are to be dynamic - for example updating the contents of one box according the the selection made in another.

Adding a Dynamic Drop-down List Box to a Web Page

Although the functionality for the combo-boxes will be written in Javascript, a little HTML is needed to create the boxes themselves:

<select id=sel_planet>
</select>
<select id=sel_moon>
</select>

The Javascript itself will consist of a number of subroutines that will:

  • add an option to a select box
  • empty a select box
  • load a select box from an array

The first of the subroutines makes the addition of an option very easy:

<script>
function add_option (select_id, text) {
var select = document.getElementById(select_id);
select.options[select.options.length] = new Option(text);
}

The second subroutine clears a combo-box (so that it can be loaded with fresh options):

function clear_combo (select_id) {
var select = document.getElementById(select_id);
select.options.length = 0;
}

The final subroutine takes an array, loops through it and adds the elements of the array as select options:

function load_combo (select_id, option_array) {
for (var i = 0; i < option_array.length; i++) {
add_option (select_id, option_array[i]);
}
}

The items required for the drop-down list can now be loaded into an array:

var planets = new Array ("Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune", "Pluto");

And then the combo-box can be loaded from the array:

load_combo ("sel_planet", planets)

If this code is placed in a .html file then the first of the combo-boxes will be populated as soon as the web page is opened.

Populating One Drop-down List Box from Another

Like the first combo-box the second one will be populated from a set of arrays:

var jupiter_moons = "Io, Europa, Ganymede," +
"Callisto, Amalthea, Himalia, Elara, Pasiphae, Sinope, Lysithea," +
" Carme, Ananke, Leda, Metis, Adrastea, Thebe, Callirrhoe, Themisto," +
"Kalyke, Iocaste, Erinome, Harpalyke, Isonoe, Praxidike, Megaclite," +
"Taygete, Chaldene, Autonoe, Thyone, Hermippe, Eurydome, Sponde," +
"Pasithee, Euanthe, Kale, Orthosie, Euporie, Aitne"
jupiter_moons = jupiter_moons.split(",");
var saturn_moons = "Titan, Rhea, Iapetus," +
"Dione, Tethys, Enceladus, Mimas, Hyperion, Prometheus, Pandora," +
"Phoebe, Janus, Epimetheus, Helene, Telesto, Calypso, Atlas," +
"Pan, Ymir, Paaliaq, Siarnaq, Tarvos, Kiviuq, Ijiraq, Thrym, Skadi," +
"Mundilfari, Erriapo, Albiorix, Suttung";
saturn_moons = saturn_moons.split(",");
var uranus_moons = "Cordelia, Ophelia, Bianca," +
"Cressida, Desdemona, Juliet, Portia, Rosalind, Belinda, Puck," +
"Miranda, Ariel, Umbriel, Titania, Oberon, Caliban, Sycorax," +
"Prospero, Setebos, Stephano, Trinculo";
uranus_moons = uranus_moons.split(",");
var neptune_moons = "Triton, Nereid, Naiad," +
"Thalassa, Despina, Galatea, Larissa, Proteus";
neptune_moons = neptune_moons.split(",");

Of course all of this needs to take place when the selection of the first drop-down list changes - this is done by assigning a subroutine to the box's onclick event:

document.getElementById('sel_planet').onclick = sel_planet_onchange;

And finally the subroutine for the onclick event is needed - this updates the second box depending on the selection in the first:

function sel_planet_onchange () {
var sel_planet = document.getElementById("sel_planet");
clear_combo ("sel_moon")
switch (sel_planet.selectedIndex){
case 2: //Earth
add_option ("sel_moon", "Moon");
break;
case 3: //Mars
add_option ("sel_moon", "Phobos");
add_option ("sel_moon", "Deimos");
break;
case 4: //Jupiter
load_combo ("sel_moon", jupiter_moons);
break;
case 5: //Saturn
load_combo ("sel_moon", saturn_moons);
break;
case 6: //Uranus
load_combo ("sel_moon", uranus_moons);
break;
case 7: //Neptune
load_combo ("sel_moon", neptune_moons);
break;
case 8:
add_option ("sel_moon", "Charon");
break;
load_combo ("sel_moon", jupiter_moons)
}
}
</script>

The web page will now show two drop-down list boxes - one of which is loaded by the Javascript code, the other will change whenever the first one is changed.

Further Reading

To see how the same functionality is achieved with VBScript read How to Create Dynamic Combo Boxes with VBScript


The copyright of the article Creating Dynamic Combo-boxes with Javascript in Javascript/Java Programming is owned by Mark Alexander Bain. Permission to republish Creating Dynamic Combo-boxes with Javascript in print or online must be granted by the author in writing.


A Dynamic Drop-Down Box, Mark Alexander Bain
A Drop-Down Box Showing a List of Planets, Mark Alexander Bain
The Contents of the Combo-Box are Dynamic, Mark Alexander Bain
   


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo

Comments
Dec 22, 2008 3:58 AM
Guest :
Nice
1 Comment: