2015-09-29 21 views
-1

我需要一些幫助才能使用JavaScript獲取Dropdown的選定索引。從@ Html.DropDownListFor獲取selectedIndex

這是我的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> 

改變下拉的時候我總是得到 「未定義」。 有沒有人有理想來解決這個問題?

+0

fyi'test'是'div'。 –

回答

1

當調用事件的處理函數時,jQuery將this設置爲目標元素。然後,您可以使用它來獲取目標元素中的selectedoption的索引。

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

'#test'是一個div。 –

+0

就是這樣,謝謝你。 – Underfaker

+0

@ DanielA.White,沒關係。它根據上下文進行選擇。 –