LayneMitch wrote:
One problem I'm working on takes an array of names from an xml file using
Ajax and writes it to <select<options tags.
This is the code they use:
function writeSelect(nam e_group) {
* *var this_option;
* *var my_select = document.getEle mentById("namel ist");
* *for (var loop = 0; loop < name_group.leng th; loop++)
* * * {
* * * * this_option = new Option();
* * * * this_option.val ue = the_array[loop];
* * * * this_option.tex t = the_array[loop]
* * * * my_select.optio ns[loop] = this_option;
* * * }
}
The parameter for writeSelect() function contains the array of names and the
id "namelist" is the id for the select tag in the form element.
This is my first time seeing the new Option() function. Is this the standard
for writing arrays to the <selecttag? Or could this have been done another
way - if so what this that way?
I'm afraid your function has a number of shortcomings.
- A better backwards compatibility can be obtained by using
'document.forms[0].elements["namelist"]' in stead of
'document.getEl ementById("name list")'.
- I surmise that your 'the_array' should read 'name_group'
- It appears you want to do a full refill of the list, since you start
looping from zero. But if your first list would be bigger than the new
one, the last entries of the first list will still be shown. It would
be better to empty the list first and then assign the new ones.
- Inside the loop, you use four lines of code for what is usually done
in one instruction.
All together:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<script type="text/javascript">
var arr = ['John', 'Paul', 'Fred', 'Mary'];
function writeSelect(nam e_group) {
var my_select = document.forms[0].elements['namelist'];
// empty the list
while (my_select.opti ons.length) my_select.optio ns[0] = null;
// populate list with the new values
for (var i=0; i<name_group.le ngth; ++i)
my_select.optio ns[my_select.lengt h]
= new Option(name_gro up[i], name_group[i]);
}
</script>
<title>My web page</title>
</head>
<body>
<form method="get" action="#">
<p>
<select size="1" name="namelist" >
<option value="-">-</option>
</select>
<input type="button" value="Click" onClick="writeS elect(arr);">
</p>
</form>
</body>
</html>
Info about the 'Option'-object:
http://www.javascriptkit.com/jsref/s...shtml#section2
Hope this helps,
--
Bart