Get value of selected drop down list item

我只是一个虾纸丫 提交于 2019-12-12 19:15:35

问题


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

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