I'm trying to force the open method and select item with select2 like this.
我正在尝试强制open方法并选择select2这样的项目。
$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
items = e.items.results;
if (items.length == 1) {
$(this).val(items[0].text);
}
});
$(".select").select2('close');
But I cannot get inside the select2-loaded evaluation and the close is happening also to quick. I want to select the first element by default if there is only one element on the list.
但我无法进入select2加载的评估,并且关闭也发生在快速。如果列表中只有一个元素,我想默认选择第一个元素。
When the 'open' occurs, it automatically performs the mechanism to get and load all the elements in my list. If I comment the close method it will take some milliseconds to display the elements on the list.
当'open'发生时,它会自动执行获取和加载列表中所有元素的机制。如果我评论close方法,则需要几毫秒才能显示列表中的元素。
But what I want is to refresh my list (this is done by the open) then I want to select only if there one element and the close my list ('select')
但我想要的是刷新我的列表(这是通过打开完成)然后我想只选择是否有一个元素和关闭我的列表('选择')
How can I achieve this? This behaviour will be trigger by a onchange event of another list. (nested selects)
我怎样才能做到这一点?此行为将由另一个列表的onchange事件触发。 (嵌套选择)
1 个解决方案
#1
6
You should move the close
call INSIDE the select2-loaded
event, so it'll only close the select element after it selected the item. Otherwise you're opening, setting event for future event, then closing immediately.
你应该在加载select2的事件中移动关闭调用,因此它只会在选择项目后关闭select元素。否则你打开,为将来的事件设置事件,然后立即关闭。
$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
items = e.items.results;
if (items.length == 1) {
$(this).val(items[0].text);
$(".select").select2('close');
}
});
#1
6
You should move the close
call INSIDE the select2-loaded
event, so it'll only close the select element after it selected the item. Otherwise you're opening, setting event for future event, then closing immediately.
你应该在加载select2的事件中移动关闭调用,因此它只会在选择项目后关闭select元素。否则你打开,为将来的事件设置事件,然后立即关闭。
$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
items = e.items.results;
if (items.length == 1) {
$(this).val(items[0].text);
$(".select").select2('close');
}
});