【问题标题】:Trying to select the value that was chosen in a drop down list using the ID of the drop down list尝试使用下拉列表的 ID 选择在下拉列表中选择的值
【发布时间】:2017-09-26 00:20:49
【问题描述】:

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>

}

【问题讨论】:

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


    【解决方案1】:

    这样试试,

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

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

    【讨论】:

    • 这意味着你&lt;option value="no value here"&gt;@(country.country在这里没有价值,先修复它然后做我所做的。
    • 我刚试了一下,第二行出现以下错误:Uncaught TypeError: Cannot read property 'options' of null
    • 我的国家/地区下拉列表已经填写了我从 ViewBag 中检索的国家/地区,它不是一个空列表。这是我单击查看页面源时得到的结果:
    • @Mouna,现在看,它只有一个 typo。我只是想念用过的eelement,让我知道它是否有效?
    • 我看到你的错字,我之前已经修复它仍然无法正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多