简体   繁体   English

尝试使用下拉列表的ID选择在下拉列表中选择的值

[英]Trying to select the value that was chosen in a drop down list using the ID of the drop down list

enter image description here I am trying to retrieve the value that was selected by the end user in a drop down list. 在此处输入图像描述,我正在尝试检索最终用户在下拉列表中选择的值。 The variable country is always null, I am using the id of the drop down list to retrieve the value that was selected by the user. 可变国家/地区始终为null,我正在使用下拉列表的ID来检索用户选择的值。

Here is the code in my view: 这是我认为的代码:

    <script>
        var country = document.getElementById("Countries");
        var value = country.options[country.selectedIndex].value;
        var text = country.options[country.selectedIndex].text;
  </script>

@Html.Label("Country", "Country")
<select name="Countries" id="Countries">
    @foreach (var country in ViewBag.countries)
    {
        <option value="@(country.country)">@(country.country)</option>
    }
</select>

} }

Try like this, 这样尝试

 <label for="Country">Country</label> <select name="Countries" id="Countries"> <option value="Iceland">Iceland</option> <option value="Kosovo">Kosovo</option> <option value="Belgium">Belgium</option> </select> 

var element = document.getElementById("Countries"); 
var selected_country_value = element.options[element.selectedIndex].value;    
alert(selected_country_value);

Demo: https://jsbin.com/poxijiluci/edit?html,js,output 演示: https : //jsbin.com/poxijiluci/edit?html,js,输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM