View Full Version : dynamic drop down in javascript

04-13-2005, 02:54 AM
I saw there were many sample codes to display dynamic drop down but there were none sample that pre-selected values when the drop down list was displayed.

Once the drop down is displayed, users can select multiple values from the drop down and the selected values are saved to the database. The next time the drop down is displayed, I want to pre-select values that users already selected and saved before.

The problem is it only pre-select the last value. For example,
obj.options[2].selected = true;
obj.options[3].selected = true;
and it display the drop down with only the 3rd value pre-selected as opposed to both 2nd and 3rd values.

However, if I put any alert() statement in there, it worked fine. That is weird.
obj.options[2].selected = true;
alert(obj.multiple); <== result is true
alert(obj.type); <== result is select-one
obj.options[3].selected = true;

Does it have to do with the drop down being out of focus or the type is select-one? How do I set the type to select-multiple? I tried obj.type="select-multiple" and it didn't like that.

Please help. Thank you.

04-14-2005, 12:26 PM
Did you set it to multiple programmatically? If you did, you need to set a little delay after setting it for the selected items to take effect.

05-31-2006, 04:01 PM
I am having the exact problem
Here is the code I have,

var newSelect = document.createElement("select");
newSelect.name = "topics[]";
newSelect.multiple = true;
newSelect.className = "inputbox";
$numRows = count( $rows );
for( $j = 0; $j < $numRows; $j++ ) {
$currRow = $rows[$j];
$html .= "newSelect.options[$j] = new Option('$currRow[topic_name]','$currRow[id]');\r\n";
$html .= ($currRow['selected'] ? " newSelect.options[$j].selected = true;" : '');
echo $html;

I tried placing a delay after setting the select to multiple, and after preselecting the options. Neither works.

Any suggestions/ideas?

Thanks for any help

06-13-2006, 09:59 PM
When you create the Option, you can specify if it's selected or not.

for( $j = 0; $j < $numRows; $j++ ) {
$currRow = $rows[$j];
$selected = ($currRow['selected'] ? "true" : "false");
$html .= "newSelect.options[$j] = new Option('$currRow[topic_name]','$currRow[id]', $selected, $selected);\r\n";
See this (http://www.devguru.com/technologies/javascript/11258.asp) for more info.