Search code examples
javascripthtmldrop-down-menuprototypejsdom-manipulation

Moving options from a <select> to a <select multiple> - the option select attribute is breaking?


I'm trying to write a plugin for Prototype where a user clicks on a dropdown and it replaces it with a multi-select element. I am almost finished with it. Everything works great until a user selects what they want displayed, and submits the form to the same page. I am using PHP to keep what the user chose selected using the selected attribute of the <option> tag. So my plugin runs after that and copies the options to the multi-select, and this is where the problem comes in. Let's say a user chose 3 items, in the html code of the multi-select all 3 items would have the selected attribute, but only the last one would be highlighted and when re-submitting the form at that point, it really only submits the highlighted one. Here is a demo. Any help on this would be great. Thanks.

HTML

<select id="test1">
    <option>Option 1</option>
    <option selected="selected">Option 2</option>
    <option selected="selected">Option 3</option>
</select>

<select id="test2" multiple="multiple">
</select>​

JavaScript

$('test1').childElements().each(function(option){
    $('test2').insert(option);
});


Solution

  • Because the first dropdown is not a multiple select, and it can have only one selected item, the DOM will be normalized, only one of the options will have the selected property set to true.

    Seems like when you copy them, the attribute is still there, so you have to read it and set the selected property accordingly.

    Never used Prototype, but I came up with something like this:

    $('test1').childElements().each(function(option){
        $('test2').insert(option);
        option.selected = $(option).readAttribute('selected');
    });
    

    jsFiddle - tested in Chrome only