javascript 获取所选下拉列表项的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15315319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:21:22  来源:igfitidea点击:

Get value of selected drop down list item

javascriptonchangehtml-select

提问by Java Player

Good Evening, i have these dynamically generated dropdown list in my JSP:`

晚上好,我的 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 但是如果我将 onChange 更改为onchange="alert(this.value)"它打印正确的值!!怎么来的?以及如何获取在 DropDown 中选择的每个项目的实际索引

回答by louisbros

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/

演示:http: //jsfiddle.net/louisbros/PS4zy/1/

回答by Mayer Spitzer

Just pass the eventobject into the Endpoint function:

只需将event对象传递给Endpoint 函数:

<select onchange="convertDropDownToTextBox(event)">
    <option value="1">Option 1</option>
</select>

And then you can access the value event.target.valuefrom within the function:

然后您可以event.target.value从函数内部访问该值:

function convertDropDownToTextBox(e) {
    console.log(e.target.value);
}