Question

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>
Was it helpful?

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

OTHER TIPS

The line

selection.selectedIndex = i;

refers to an undeclared variable. You want to refer to sel1O

sel1O.selectedIndex = i;

In addition, putting a break afterwards will break you out of the for loop which is probably not the behavior you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top