How to use Javascript to create Dynamic Drop-Down Lists

in #utopian-io8 years ago (edited)

Dynamic drop-down lists can improve the user experience on any web site - and the programmer can make them dynamic by using Javascript.

What Will I Learn?

Creating Dynamic Combo-boxes with Javascript

Requirements

Nodejs

Difficulty

Intermediate

Tutorial Contents

  • Adding a Dynamic Drop-down List Box to a Web Page
  • Populating One Drop-down List Box from Another

Creating Dynamic Combo-boxes with 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.

image.png

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.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

I gave you some lovin How bout you give me some too?

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • JavaScript is not open source.
  • your selected repository is wrong too. Node.js is not correct.
    You can contact us on Discord.
    [utopian-moderator]

Coin Marketplace

STEEM 0.13
TRX 0.33
JST 0.034
BTC 110762.15
ETH 4299.54
USDT 1.00
SBD 0.82