Javascript 从@Html.DropDownListFor获取selectedIndex
我需要一些帮助来使用JavaScript获取下拉列表的选定索引 这是我的Javascript代码:Javascript 从@Html.DropDownListFor获取selectedIndex,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我需要一些帮助来使用JavaScript获取下拉列表的选定索引 这是我的Javascript代码: <script type="text/javascript"> $(function () { $("#test").change(function () { var index = document.getElementById('test').selectedIndex; alert(index); }); }); $(函数(
<script type="text/javascript">
$(function () {
$("#test").change(function () {
var index = document.getElementById('test').selectedIndex;
alert(index);
});
});
$(函数(){
$(“#测试”)。更改(函数(){
var index=document.getElementById('test')。selectedIndex;
警报(索引);
});
});
下面是下拉列表:
<div class="editor-field" id="test">
@Html.DropDownListFor(x => x.TestID, new SelectList(Model.Tests, "TestID", "TestName"))
@Html.ValidationMessageFor(model => model.TestID)
</div>
@DropDownListFor(x=>x.TestID,新选择列表(Model.Tests,“TestID”,“TestName”))
@Html.ValidationMessageFor(model=>model.TestID)
更改下拉列表时,我总是“未定义”。
有人有办法解决这个问题吗?当调用事件的处理程序时,jQuery将
这个
设置为目标元素。然后,您可以使用它来获取目标元素内部的所选选项的索引
$("select", "#test").change(function () {
var index = $("option:selected", $(this)).index()
alert(index);
});
仅供参考test
是一个div
。谢谢。@DanielA.White,没关系。它根据上下文进行选择。#test
不应触发更改事件,或者不保证。@DanielA.White,很好。再次修复了上下文。