我使用 select2 作为带有 bootstrap 和 bootbox 的下拉菜单。问题是,当我显示下拉列表并尝试第一次选择一个值时,它返回一个空对象。如果我重新选择其他值,它就可以正常工作。有什么想法可以解决这个问题吗?
我的代码如下
<select name="classSelect" class="form-control classSelect select2-hidden-accessible" id="subject_change_select" tabindex="-1" aria-hidden="true">
<option value="5">sdfsdfsfsdf</option>
<option value="6">2</option>
<option value="7" selected="">1</option>
<option value="8">3</option>
<option value="9">4</option>
</select>
$(element).select2({
language: "en",
minimumResultsForSearch: 1,
theme: "classic"
}).select2('open');
我尝试使用以下代码获取数据:
$('#subject_change_select').select2('data')
或
$('#subject_change_select').val()
最佳答案
使用 jquery .change()
获取所选输入的值。
然后,使用 .text()
获取文本值。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$( document ).ready(function() {
$( "#subject_change_select" ).change(function() {
r = $("#subject_change_select option:selected").text();
console.log(r);
});
});
</script>
</head>
<body>
<select name="classSelect" class="form-control classSelect select2-hidden-accessible" id="subject_change_select" tabindex="-1" aria-hidden="true">
<option value="5">sdfsdfsfsdf</option>
<option value="6">2</option>
<option value="7" selected="">1</option>
<option value="8">3</option>
<option value="9">4</option>
</select>
</body>
</html>
关于Javascript select2 在第一次选择时选择的值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44141039/