How can I determine the value of the selected dropdown option using getElementsByClassName?

。_饼干妹妹 提交于 2021-02-08 10:30:28

问题


How can I determine the value of the selected dropdown options using javascript. I can't use id selector so I was trying with document.getElementsByClassName. I understand that returns a set of values. Here is a simplified code I am trying to use:

<div id="MDL" class="dates">
<p>Select Dates and Price</p>
<select class="datevalue">
    <option value="30">17th July - &pound;30</option>
    <option value="45">17th July - &pound;45</option>
    <option value="70">17th July - &pound;70</option>
    <option value="30">18th July - &pound;30</option>
    <option value="45">18th July - &pound;45</option>
    <option value="70">18th July - &pound;70</option>
</select>
</div>
<input type="button" id="book" VALUE="Buy Now" onClick="book()">

function book() {
var e = document.getElementsByClassName('datevalue');
alert(e.options[.selectedIndex].value);

}

But it doesn't work. I've red all the related questions so please do not send me a link to an other question.


回答1:


document.getElementsByClassName returns a HTMLCollection. Even if you have just one element, it's e[0], not e.




回答2:


To get the first element in the HTMLCollection returned by getElementsByClassName, use [0]. And then get its value.

document.getElementsByClassName('datevalue')[0].value



回答3:


if what you mean by value is the text inside option then use the following code instead :

alert(e.options[e.selectedIndex].text);

I.E. change value to text.



来源:https://stackoverflow.com/questions/30445916/how-can-i-determine-the-value-of-the-selected-dropdown-option-using-getelementsb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!