2009-10-12 143 views
2

我有一個下拉如何在javascript中的下拉列表中預先選擇一個選項?

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"); 
} 

什麼是選項「貝納維德斯園」爲默認值的代碼這個代碼? 在HTML是這樣的

selected="selected" 

怎麼樣在JavaScript?

+0

檢出此問題http://stackoverflow.com/questions/149573/check-if-option-is-selected-with-jquery-if-not-select-a - 默認 – eKek0 2009-10-12 22:13:08

回答

5

你需要使用

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

保持在1眼在右邊。這就是來選擇

+0

該值需要不同的假,只是 – 2009-10-12 22:14:09

+0

謝謝你的答案。但如果我想驗證,如果選擇的值是例如'選擇你的價值',這是標準值,它是這樣的: 'selbox.options [selbox.options.length] =新選項('選擇你的價值' ,'',1);'就像你說的。我將如何做到這一點。現在我有這個。 'if(sel == null || sel ==「」) \t { \t alert(「下拉列表不能爲空。 \t return false; \t}' 但它仍然接受表單提交。同時仍然提供警報。 – BRoebie 2015-11-16 12:27:34

0

試試這個:

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

我可以建議你讓你的代碼更加清晰,就像這樣:

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)); 
} 

對我來說這只是感覺,因爲每當你想改變一個更好值,那麼你只需要改變它在數組中的值。而且這也可以重構爲一個函數,它只接受一個數組和加載項的選擇框。

(在Chrome中測試過,但應該可以在大多數地方工作;在w3schools上有一個黑客可以在IE6上找到它,並且,如果選擇框中有項目,那麼它們將保留。首先用以下代碼清除它:http://www.plus2net.com/javascript_tutorial/list-remove.php

相關問題