views:

107

answers:

2

Hi,

Can anyone please tell me how do I make this script run in IE 7? When I run this , nothing happens.

    <html>
    <head>
    <script language="JavaScript">
    function moveSelectedOption() {
        // Fetch references to the <select> elements.
        var origin = document.getElementById('origin_select');
        var target = document.getElementById('target_select');


        // Fetch the selected option and clone it.
        var option = origin.options[origin.selectedIndex];

       var copy = option.cloneNode(true);

        // Add the clone to the target element.
        target.add(copy, null);
    }
    </script>
</head>
<body>
    <select id="origin_select" multiple>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
    <select id="target_select" multiple>

        <option value="C1">C1</option>
    </select>
    <button onclick="moveSelectedOption()">Add</button>
 <!--   <input type="button" onClick="moveSelectedOption()" value="AddMeToo" />  this does not work either-->
    </body>
    </html>
A: 
rahul
Thanks. This worked. Can you please tell me what was the problem with my version?
JPro
See my edited answer.
rahul
@JPro accept this answer if it worked
c0mrade
+2  A: 

Firstly, you can't use add(option, null) in IE-up-to-7 due to a bug (you get “Type mismatch”). You would have to use add(option), but of course that's non-standard and breaks elsewhere. So to be safe, use select.add(option, options.length), or select.options[options.length]= option.

Next, you can't add an option to a select when that option has already been in a select in IE-up-to-7 (even after cloning!) due to another bug (you get “Invalid argument”). IE's handling of <option> elements is off in a lot of ways, the source of which is that IE's select boxes are native Windows widgets, not objects implemented by the browser. Consequently IE's HTMLOptionElement interface is only a façade, that often slips.

The safe way to handle option elements is to create them anew each time, either using document.createElement and writing the value and text properties, or using the old-school new Option() constructor as in rahul's answer.

Finally, you shouldn't use selectedIndex on a <select multiple>. Since there isn't necessarily one-and-only-one selection it doesn't make sense in any browser. (For example, clicking the Add button with no selection gives an error.) Instead, loop over all options and copy each option that is .selected.

bobince
thanks for the explanation.
JPro