View Full Version : Dynamically populating the list boxes

11-03-2006, 06:12 AM
Hi all,

Please provide an idea of how to build dynamic list boxes using Javascript.

I have 2 list boxes containing Origin and Destination of flights. If i select one Origin country then , second list box must populate only those countries which have flights.

In the http://www.ryanair.com/site/EN/ site, If I select "Aarhus" as origin and it will show only 2 countries "Barcelona" & "London". When i see the code, it has pre-assigned arrays, whenever OnClick is triggered it is calling the function and populating the array values.

But i need to populate the destinations from the database everytime i select the origin from the listbox 1. Simply saying that I can't hardcode the origin and destination arrays , as i need to get them from the database...

Any help or suggestions are appreciated...


11-03-2006, 12:13 PM
Something like this?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var myval = [];
myval['India']=['Bombay','Calcutta','Hyderabad','Jaipur','New Delhi'];
// and so on...
function newOpt(v){//main function
var root = document.getElementById('cities');
removeEl(root);//removes the old childNodes
for(var i=0;i<myval[v].length;i++){
var opt = createEl('option');//creates option element
var txt = document.createTextNode(myval[v][i])//creates textNode
opt.appendChild(txt);//appends textNode
createAt(opt,'value',myval[v][i])//sets the attribute
root.appendChild(opt)//appends the element
function removeEl(obj){
function createEl(el){
return this.obj;
function createAt(obj,att,val){
<select id="countries" onchange="if(this.selectedIndex>0){newOpt(this.value)}">
<option value="">-- Select a country -- </option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>

<select id="cities">