Search code examples
javascriptselectedindex

How to set .selectedIndex of select element using array field?


My script seems to do what I need, EXCEPT, marking the selected option as 'selected' or 'selected=selected'.

Note: One of the objects in themeInfo has [4] set to 'selected'

    <script type='text/javascript'>
    var themeInfo = [
        ['Default', 'Default Template', 'Default.png', '&template=Default', ''],
        ['Desert', 'The Desert', 'Desert.png', '&template=Desert', 'selected'],
        ['Red', 'Big Red', 'Red.png', '&template=Red', '']
    ];
    window.onload = function(){

        var sel1O = document.getElementById('sel1');

        var themeList = document.getElementById('sel1'); //
        var selectedTheme = themeList.options[themeList.selectedIndex].value; //

        for(i=0; i<themeInfo.length; i++){
            sel1O.options[sel1O.options.length] = new Option(themeInfo[i][0], themeInfo[i][0], false, themeInfo[i][4] == 'selected');

                /* Need to mark option selected -DOESN'T WORK */
                //if (themeInfo[i][4] == 'selected') { //
                //    selection.selectedIndex = i; //
                //} //

        }
    }
    </script>


    <form id='skinselectorform' action='home.php' method='POST'>
            <select name='template' id='sel1'>
                <option>Select below...</option>
            </select>
            <input type='submit' class='button' value='GO'>
    </form>

Solution

  • You should be setting the selected argument of new Option(), not the selectedIndex

    var themeInfo = [
      ['Default', 'Default Template', 'Default.png', '&template=Default', ''],
      ['Desert',  'The Desert',       'Desert.png',  '&template=Desert',  'selected'],
      ['Red',     'Big Red',          'Red.png',     '&template=Red',     '']
    ];
    
    window.onload = function () {
        var sel1O         = document.getElementById('sel1');
        var themeList     = document.getElementById('sel1');
    
        for (i = 0; i < themeInfo.length; i++) {
          var selected = themeInfo[i][4] == 'selected';
          var option = new Option(themeInfo[i][0], themeInfo[i][0], false, selected);
          sel1O.options[sel1O.options.length] = option
        }
    }
    

    FIDDLE