我有一个下拉列表,如下所示:
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>
我有同样的课程,如上所述。我想要做的是获取索引和选择的索引值。为此,我的jQuery代码如下
$('.sn-item-reveived-ddl').change(function () {
var value = $(this).val(); //this brings back the correct value of the dropdown
var index = $('option:selected').index(); //if i use this it keeps returning index 0
console.log(index);
});
我遇到的问题是我可以使用this
关键字获取正确的值,但是如果我尝试获取索引,它会使用名为sn-item-received-ddl
的类获取第一个下拉列表的索引。请问有人告诉我哪里出错了。
答案 0 :(得分:1)
将this
添加到$('option:selected')
,使其看起来像$('option:selected', this)
然后它应该有效。
然后它将在您刚刚更改的下拉列表中获取所选选项的索引。
$('.sn-item-reveived-ddl').change(function() {
var value = $(this).val(); //this brings back the correct value of the dropdown
var index = $('option:selected', this).index(); //if i use this it keeps returning index 0
console.log(index);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>
&#13;