Get selectedIndex from @Html.DropDownListFor

Get selectedIndex from @Html.DropDownListFor

本文关键字:DropDownListFor @Html from selectedIndex Get      更新时间:2023-09-26

我需要一些帮助来获得使用JavaScript的下拉菜单的选定索引。

这是我的Javascript代码:
<script type="text/javascript">
$(function () {
    $("#test").change(function () {
        var index = document.getElementById('test').selectedIndex;
        alert(index);
    });
});

这是下拉菜单:

<div class="editor-field" id="test">
                            @Html.DropDownListFor(x => x.TestID, new SelectList(Model.Tests, "TestID", "TestName"))
                            @Html.ValidationMessageFor(model => model.TestID)
                        </div>

当改变下拉菜单时,我总是得到"未定义"。有人有解决这个问题的办法吗?

当调用事件处理程序时,jQuery将this设置为目标元素。然后,您可以使用它来获取目标元素内selected option的索引。

$("select", "#test").change(function () {
    var index = $("option:selected", $(this)).index()
    alert(index);
});