Select2不显示所选值 [英] Select2 doesn't show selected value
问题描述
Select2成功地从列表中加载了所有项目,这是在页面加载时尝试选择特定值时发现的问题.示例:
Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:
::将select2放在特定的html元素中,即使加载了所有项目,也不会选择任何值.
:: put select2 in a specific html element, no value is selected even all items are loaded.
$('#my_id').select2();
::加载页面时,我试图显示一个选定的特定项目,但无法按预期方式工作,因为即使选中该项目,select2也不会显示该项目.
:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.
$('#my_id').val('3'); //select the right option, but doesn't render it on page loads.
如何使选定的选项在页面加载时弹出?
How to make a selected option to pop up when pages loads?
谢谢.
::我如何加载所有select2项(对不起,它的翡翠,不是纯HTML):
:: How I load all select2 items (sorry, its jade, not pure HTML):
label(for='category') Category
span.required *
select(id='category', style='width:230px', name='category')
option(value='') - Select -
each cat in categories
option(value='#{cat.id}') #{cat.description}
P.S .:我列表中的所有物品都已装载.
P.S.: All items from my list are loaded.
::我如何初始化select2:
:: How I initialize the select2:
只需将以下行代码放在我的javascript上,即可成功:
Just put the following line code on my javascript and it does successful:
$('#category').select2();
::我如何选择一个特定值:
:: How I'm trying to select a specific value:
-
第一次尝试:
First attempt:
$('#category').select2(
{
initSelection: function(element, callback) {
callback($('#field-category').val());
}
}
);
第二次尝试:
Second attempt:
$('#category').val($('#field-category').val());
P.S .: #field-category
的值是一个隐藏的输入字段,并且可以正常工作.
P.S.: #field-category
has a value its a hidden input field and works OK.
谢谢,伙计们!
推荐答案
您需要使用 initSelection 选项设置初始值.
You need to use the initSelection option to set the initial value.
如果使用预定义的select
元素创建select2,则可以使用以下方法
If you are using a pre-defined select
element to create the select2, you can use the following method
$('select').select2().select2('val','3')
演示:小提琴
这篇关于Select2不显示所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!