简体   繁体   English

Select2 Select函数显示以前的值

[英]Select2 Select Function Shows Previous Value

I'm using Select2 as a searching dropdown, however when I select an item in the list it keeps showing the previous value. 我使用Select2作为搜索下拉菜单,但是当我在列表中选择一个项目时,它会一直显示先前的值。

I initialize the Select2 dropdown: 我初始化Select2下拉列表:

$(document).ready(function() {
  $(".ordersSelect").select2();
});

And then set all the options: 然后设置所有选项:

<select class="ordersSelect" style="width:75%;">
  <option value>Select a priority...</option>
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>

So let's say I select 1, my console from this code: 因此,假设我从以下代码中选择1,即我的控制台:

// when value is selected
$('.ordersSelect').on('select2:selecting', function(e) {
  var prioritySelection = $('.ordersSelect').select2('data')[0].text;
  console.log("DATA: " + prioritySelection);
});

Will show "DATA: Select a priority...". 将显示“ DATA:选择优先级...”。 If I then select say '3', the console will show "DATA: 1". 如果然后选择说“ 3”,则控制台将显示“ DATA:1”。

It keeps on showing the value from the previous selection. 它继续显示上一个选择的值。 When I change "select2:selecting" to "select2:selected" the console message just never comes up. 当我将“ select2:selecting”更改为“ select2:selected”时,控制台消息永远不会出现。

What am I doing wrong here..? 我在这里做错什么了..?

First, you should definitely use select2:select . 首先,您绝对应该使用select2:select
select2:selecting is triggered before the result is selected.. select2:selecting结果之前触发选择。

$('select').on('select2:select', function (evt) {
  // Do something
});

Second, you can get the data object/value from the event itself. 其次,您可以从事件本身获取数据对象/值。 Check the evt.params.data property. 检查evt.params.data属性。

Got it using: 使用以下命令得到它:

$('.ordersSelect').select2().on("change", function(e) {
  var obj = $(".ordersSelect").select2("data");
  console.log("change val=" + obj[0].id);  // 0 or 1 on change
});

If anyone knows of a better way though, I am definitely up to hear it. 如果有人知道更好的方法,我肯定会听到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM