2011-11-16 105 views
0

我有一个选择框,我想尝试获取当前选定选项的索引。 我可以得到这个值。如何查找选定列表中当前选项的索引

(#mySelectBox).val();

我后来是如果val被默认设置为最后一个选项,这将是option3我想获得该选项的索引。

<div class="selectItems"> 
     <select id="mySelectBox"> 
      <option value="0">option1</option> 
      <option value="1">option2</option> 
      <option value="2">option3</option> 
     </select> 
    </div> 

回答

0
$('#mySelectBox option:selected').val(); 
1

this blog:

// Get the text of the selected item 
alert($("#myselect option:selected").text()); 

// Get the value of the selected item 
alert($("#myselect option:selected").val()); 

// Get the index of the selected item 
alert($("#myselect option").index($("#myselect option:selected"))); 

或者jQuery的> = 1.6:

alert($('#myselect').prop('selectedIndex'); 

但是有什么用时,你可以得到的值或文本索引选择?如果你特别想知道,如果它的第一个或最后一个,也许......

alert($('#myselect option:selected').val() === $('#myselect option:first').val()); 
alert($('#myselect option:selected').val() === $('#myselect option:last').val()); 
1

我想你要找的是什么.selectedIndex财产。如果您对选择框的变化事件,你可以做这样的事情:

$('select').change(function() { 
    var currentIndex = this.selectedIndex; 
}); 

这将返回2选项3

好运。

0

试试这个 - >http://jsfiddle.net/p6Jfb/

脚本:

$("#mySelectBox").change(function() { 
    console.log($(this).get(0).selectedIndex); // prints the currently selected index 
}) 
0

$(function(){ 
 
    
 
    $('#mySelectBox').on('change',function(){ 
 
     console.log('Selected Value '+$('#mySelectBox option:selected').val()) 
 
     
 
     console.log('Selected Text '+$('#mySelectBox option:selected').text()) 
 
     
 
     console.log('Selected Index '+$('#mySelectBox option:selected').index()) 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="selectItems"> 
 
     <select id="mySelectBox"> 
 
      <option value="0">select</option> 
 
      <option value="1">option1</option> 
 
      <option value="2">option2</option> 
 
      <option value="3">option3</option> 
 
     </select> 
 
    </div>

试试这个。

相关问题