使用JavaScript获取选项文本/值

答案var option_user_selection = element.options[element.selectedIndex].text

我正在试图build立一个表格来填充一个人的命令。

 <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> 

我想要做的是发送select对象,拉选项菜单中的名称和文本/值和选项标签中的数据。

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

我可以得到名称和选项值,但我似乎无法从select对象中获取text =“”或value =“”。 我只需要用户select的选项菜单中的文本/值。 我知道我可以把它们放在一个数组中,但是这没有帮助

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

我还需要使用传入的select参数,因为它是如何在我的代码中设置的。

稍后,将使用该文本/值来拉动将dynamic填充下一个select表单的XML文档。

您可以使用:

 var option_user_selection = element.options[ element.selectedIndex ].text 

在jQuery中,你可以试试这个$("#select_id>option:selected").text()

 form.MySelect.options[form.MySelect.selectedIndex].value 
 var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text