我无法实时记录在select2输入字段中输入的内容
我的目标是在用户输入select2搜索框
时更新另一个输入字段我尝试过很多东西,但它不起作用: 我的控制台中没有出现任何内容
$('.mySelect2').on("change",function(e){
console.log("mySelect2 text", e.target.value)
console.log("mySelect2 text $(this).val()", $(this).val())
// #location is my other field that I want to update
$("#location").text(e.target.value);
});
答案 0 :(得分:2)
根据documentation,您需要使用不同的事件:
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
更新:以下方法允许捕获用户在select2输入中输入的所有内容
// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
var $select2 = $('.js-example-basic-single')
$select2.select2();
$('body').on('input', '.select2-search__field', function() {
console.log(this.value);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<select class="js-example-basic-single" name="state">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
&#13;