Jump to content

[JS] Set an option element as selected

- - - - -

  • Please log in to reply
1 reply to this topic

#1
Alhazred

Alhazred

    Learning Programmer

  • Members
  • PipPipPip
  • 99 posts
I have a form and I generate a select menu with javascript.
I need to select by default an option element passed as parameter to the page with the form.
Now I've got this code
function setZone(zone)
{
    var zoneBox = document.getElementById("zone");
    zoneBox.options.length = 0;
    zoneBox.options[0] = new Option("- Seleziona zona -", "");
    if(zone != "")
    {
        var arrZone = zone.split(",");
        for(i = 0; i < arrZone.length; i++)
        {
            if(arrZone[i] != "")
            {
                zona = arrZone[i];
                if(zona == sel_zone) { //sel_zone is the parameter received by the page
                    zoneBox.options[zoneBox.options.length] = 
                    new Option(zona, zona.replace(" ","_")); //I need to make this selected!
                }
                else {
                    zoneBox.options[zoneBox.options.length] = 
                    new Option(zona, zona.replace(" ","_"));
                }
            }
        }
    }
}
The code will execute only once the instruction inside the "if(zona == sel_zone)" and that option element must be set as "selected", how can I do that?

#2
gokuajmes

gokuajmes

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 518 posts
well you can just do this
var ctrlDDL = document.getElementById("dropdownlistID");
ddl.selectedIndex = 2;
//this will select second element in the drop down list





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users