Forum Moderators: open

Message Too Old, No Replies

Difficulty adding to dropdown in IE

         

garann

6:56 pm on Nov 3, 2005 (gmt 0)

10+ Year Member



I have this function that's throwing an error when it hits the line noted in the comment. It's supposed to remove an element from one dropdown and add it to another dropdown:

function addItem(mainID) {
var main = document.getElementById(mainID);
var sub = document.getElementById(mainID + "_sub");
var current = main.options[main.selectedIndex];
if (document.all)
sub.add(current); // error
else
sub.options[sub.length] = current;
}

The error is "invalid argument" and only shows up in IE (cause that line is hopefully only being seen by IE). Does anyone see what I've done wrong?

Thanks!
g.

ajkimoto

10:21 pm on Nov 3, 2005 (gmt 0)

10+ Year Member



garann,

How about something like this? We first create a new option object, then add it to the target select. This code should work in IE and FF/Moz.

<script type="text/javascript">
<!--
//no need for different code for IE and FF/Moz
function addItem(mainID) {
var main = document.getElementById(mainID);
var sub = document.getElementById(mainID + "_sub");
var current = main.options[main.selectedIndex];

//create new option
newOptionName=new Option(current.value,current.value,false,true);

//attach option as the last option in the target select
sub.options[sub.options.length]=newOptionName
}

//-->
</script>

</head>

<body>
<select id="mySel">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
</select>

<select id="mySel_sub">
<option value="test4">test4</option>
<option value="test5">test5</option>
<option value="test6">test6</option>
</select>
<button onclick="addItem('mySel')">add item</button>
</body>

Hope this helps,

ajkimoto