View Full Version : Using Javascript to Dynamically Populate Select Lists

02-11-2007, 02:41 AM
I was looking around for a way for my users to select an option from one select box, and depending on what option they chose, it would fill the second select box with certain options. I tried one script first, but it was worthless and cluttered. I finally googled for dynamically created select boxes, and I found a script that is very, very easy to customize and use...especially if you're wanting to put the options in via PHP, like I did with this script. Hope this helps someone!


Here's the code:

<script language="Javascript">

function PopulateTeams() {

var SportsList = document.frmMain.Sports;

// Clear out the list of teams

if (SportsList[SportsList.selectedIndex].value == "1") {
AddToOptionList(document.frmMain.Teams, "1", "Oakland Athletics");
AddToOptionList(document.frmMain.Teams, "2", "San Francisco Giants");

if (SportsList[SportsList.selectedIndex].value == "2") {
AddToOptionList(document.frmMain.Teams, "3", "Oakland Raiders");
AddToOptionList(document.frmMain.Teams, "4", "San Francisco 49ers");

if (SportsList[SportsList.selectedIndex].value == "3") {
AddToOptionList(document.frmMain.Teams, "5", "Golden State Warriors");
AddToOptionList(document.frmMain.Teams, "6", "Minnesota Timberwolves");

function ClearOptions(OptionList) {

// Always clear an option list from the last entry to the first
for (x = OptionList.length; x >= 0; x = x - 1) {
OptionList[x] = null;

function AddToOptionList(OptionList, OptionValue, OptionText) {
// Add option to the bottom of the list
OptionList[OptionList.length] = new Option(OptionText, OptionValue);


<form name="frmMain">

<select name="Sports" onChange="PopulateTeams();" size="4">
<option>Choose a Sport</option>
<option value="1">Baseball</option>
<option value="2">Football</option>
<option value="3">Basketball</option>

<select name="Teams" size="3">
<option> </option>


02-11-2007, 08:01 AM
Try this:

<script type="text/javascript">
function popSecond()
var secBox,second,objvalue;
var obj = document.all.first;
objvalue = obj.options[obj.selectedIndex].value;
if(objvalue == "1")
secBox = "First,Second,Third,Fourth,Fifth,Sixth";
if(objvalue == "2")
secBox = "Something,Else,In,Here";
if(objvalue == "3")
secBox = "This,Is,The,Third,Box";
secBox = secBox.split(",");
second = '<select name="second">';
for(var i=0;i<secBox.length;i++)
second += "<option>" + secBox[i] + "</option>"
second += "</select>";
document.getElementById("second").innerHTML = second;
<select name="first" onChange="popSecond()">
<option value="">Select one option</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<div id="second">

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum