How to preselect an option in a dropdown in javascript?

I have this code for a dropdown menu

if (chosen == "Parade") {
  selbox.options[selbox.options.length] = new Option("Select Venue","");
  selbox.options[selbox.options.length] = new Option("Benavides Park","Benavides Park");
  selbox.options[selbox.options.length] = new Option("CME Auditorium","CME Auditorium");
  selbox.options[selbox.options.length] = new Option("Engineering Sports Complex","Engineering Sports Complex");
  selbox.options[selbox.options.length] = new Option("Field in front of Grandstand","Field in front of Grandstand");
  selbox.options[selbox.options.length] = new Option("Plaza Mayor","Plaza Mayor");
  selbox.options[selbox.options.length] = new Option("Quadricentennial Park","Quadricentennial Park");
  selbox.options[selbox.options.length] = new Option("Rectors Hall","Rectors Hall");
  selbox.options[selbox.options.length] = new Option("Seminary Gym","Seminary Gym");
  selbox.options[selbox.options.length] = new Option("Tinoco Park","Tinoco Park");
  selbox.options[selbox.options.length] = new Option("UST Grandstand","UST Grandstand");
  selbox.options[selbox.options.length] = new Option("UST Gymnasium","UST Gymnasium");
  selbox.options[selbox.options.length] = new Option("Venue not listed/outside UST","Venue not listed/outside UST");
}

      

What is the default code for the "Benavides Park" option? in html like it

selected="selected"

      

like in javascript?

+2


source to share


3 answers


you need to use

new Option("UST Grandstand","UST Grandstand", 1);

      



Follow the 1 on the right. thats means chosen

+5


source


May I suggest making your code cleaner, for example:

var selectedItem = -1; // change to select different item
var options = ["Benavides Park", "CME Auditorium", "Engineering Sports Complex", "Field in front of Grandstand", "Plaza Mayor", "Quadricentennial Park", "Rectors Hall", "Seminary Gym", "Tinoco Park", "UST Grandstand", "UST Gymnasium", "Venue not listed/outside UST"];

selbox.add( new Option("Select Venue", "", (-1 == selectedItem) ? 1 : 0));
for (var i = 0; i < options.length; i++) {
   selbox.add( new Option(options[i], options[i], (i == selectedItem) ? 1 : 0) );
}

      



This seems nicer to me, because whenever you want to change a value, you just change its value in the array. And this can also be refactored into a native function that just takes an array and a select box to load the items into.

(Tested in chrome but should work in most places, there is a hack you can find at w3schools to fix it for IE6. Also, if there are items in the select box, it will stay. You might want to clean this up first with code from here: http://www.plus2net.com/javascript_tutorial/list-remove.php )

+1


source


try this:

var foo = document.getElementById('yourSelect');
if (foo)
{
  foo.selectedIndex = 0;
}

      

0


source







All Articles