i have this code for a dropdown
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.optio开发者_开发问答ns[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 code for the option "Benavides Park" to be the default value? in html it's like this
selected="selected"
how about in javascript?
you need to use
new Option("UST Grandstand","UST Grandstand", 1);
keep the eye on the 1 at the right. thats means selected
May I suggest that you make your code cleaner, like so:
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) );
}
To me this just feels nicer because whenever you want to change a value then you just change its value in the array. And this can also be refactored into a function on it's own that merely accepts an array and the select box to load items into.
(Tested in chrome but should work in most places; there is a hack that you can find on w3schools to fix it for IE6. Also, if the select box has items in it then they will remain. You might want to clear it first with code from here: http://www.plus2net.com/javascript_tutorial/list-remove.php)
try this:
var foo = document.getElementById('yourSelect');
if (foo)
{
foo.selectedIndex = 0;
}
精彩评论