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

时间:2017-09-25 15:47:57

标签: javascript asp.net drop-down-menu

enter image description here我正在尝试检索最终用户在下拉列表中选择的值。变量country始终为null,我使用下拉列表的id来检索用户选择的值。

以下是我视图中的代码:

    <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>

}

1 个答案:

答案 0 :(得分:0)

试试这个,

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

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

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