问题
Good Evening, i have these dynamically generated dropdown list in my JSP:`
<td><select name="model" id="model" onchange="convertDropDownToTextBox()">
<c:forEach items="${model_list}" var="item">
<option value="${item.modelId}">${item.modelName}</option>
</c:forEach>
<option value="100">Add New Model</option>
</select></td>
and i tried these script to get the selected value from these dropdown :
function convertDropDownToTextBox(){
var select = document.getElementById("model");
var selectedString = select.options[select.selectedIndex].value;
alert(selectedString);
}
the problem here is that it always gives 1 for every item selected in the dropdown however i f i changed the onChange to be onchange="alert(this.value)"
it prints the right values!! how that come? and how to get the actual index of every item selected in the DropDown
回答1:
Not exactly sure what the problem is but this works for me:
var select = document.getElementById("model");
select.onchange = function(){
var selectedString = select.options[select.selectedIndex].value;
alert(selectedString);
}
Demo: http://jsfiddle.net/louisbros/PS4zy/1/
回答2:
Just pass the event
object into the Endpoint function:
<select onchange="convertDropDownToTextBox(event)">
<option value="1">Option 1</option>
</select>
And then you can access the value event.target.value
from within the function:
function timeFrameChanged(e) {
console.log(e.target.value);
}
来源:https://stackoverflow.com/questions/15315319/get-value-of-selected-drop-down-list-item