2011-01-09 121 views
48

回答選項的文本/值:var option_user_selection = element.options[element.selectedIndex].text掌握JavaScript的

我試圖建立在一個人的順序填寫表格。

<form name="food_select"> 
    <select name="maincourse" onchange="firstStep(this)"> 
     <option>- select -</option> 
     <option text="breakfast">breakfast</option> 
     <option text="lunch">lunch</option> 
     <option text="dinner">dinner</option> 
    </select> 
</form> 

我想要做的是發送選擇對象,從選項菜單中拉出名稱和文本/值和選項標記中的數據。

function firstStep(element) { 
    //Grab information from input element object 
    /and place them in local variables 
    var select_name = element.name; 
    var option_value = element.value; 
} 

我能得到的名稱和選項值,但我似乎無法得到從選擇對象的文本=「」或值=「」。我只需要用戶選擇的選項菜單中的文本/值。我知道我可以將它們放置在一個數組,但這並不能幫助

var option_user_selection = element.options[ whatever they select ].text 

我還需要使用傳入的選擇參考,因爲這是它是如何建立在我的代碼的其餘部分。

稍後,將使用該文本/值來拉動將動態填充下一個選擇表單的XML文檔。

+3

http://stackoverflow.com/questions/1085801/how-to-get-the -selected-value-of-dropdownlist-using-javascript – trante 2014-02-04 18:58:03

+0

使用jQuery你可以做類似`jQuery('#mySelect option [value = myValue]') – 2015-07-15 18:58:52

+3

[Retrieving the text of the selected