问题
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 - £30</option>
<option value="45">17th July - £45</option>
<option value="70">17th July - £70</option>
<option value="30">18th July - £30</option>
<option value="45">18th July - £45</option>
<option value="70">18th July - £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