PDA

View Full Version : Populate option of <select>



d4d4ng
04-10-2006, 01:10 PM
Hi All,

I have an array1 like this :

var array1 =
[["Select Number"],
["One"],
["Two"]]

How do I code, so array1 elements will populate onLoad the options of <select> like :

<select name="s1">
<option name="option1">One
<option name="option2">Two
</select>

Thanks in advance.
Amri

jscheuer1
04-10-2006, 02:07 PM
Name is not a valid attribute of the option element so, I have used id instead. In other words, the created options will have the id of option0, option1, option2 - rather than name.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
onload=function(){
var array1 =
["[Select Number]",
"One",
"Two"]
for (var i_tem = 0; i_tem < array1.length; i_tem++){
array1[i_tem]=[array1[i_tem], document.createElement('option')]
array1[i_tem][1].id='option'+i_tem
array1[i_tem][1].appendChild(document.createTextNode(array1[i_tem][0]))
document.getElementById('toFill').appendChild(array1[i_tem][1])
}
}
</script>
</head>
<body>
<select id="toFill" name="s1" onchange="alert(this.options[this.selectedIndex].id)">
</select>
</body>
</html>

The onchange event for the select is just a test to see if the id attributes were correctly assigned.

d4d4ng
04-10-2006, 02:19 PM
Hi jscheuer1,

Wow, it was a quick answer :) . Appreciated your help in sovling my problem.
I will implement your code and backwith later with result.

Thans again and may God bless you.

Amri