如何使用自定义输入填充 select2
How to populate select2 with custom input
我实现了一个 select2
下拉列表,允许用户输入自定义输入...
$("#select").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
multiple: false,
selectOnBlur: true,
data: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
});
这很好用,但在某些情况下,我需要以编程方式为 select2
下拉列表设置自定义值。我尝试执行以下操作...
// Doesn't work
$('#select').val('val', custom);
// Doesn't work
$('#select').val(custom);
有什么办法吗?
正在处理 fiddle 我的 select 下拉菜单。
是否要显示所选值?如果是这样你可以添加
$('#select').val(custom).attr("selected", "selected").change();
如果我没记错的话,你需要触发select2的更改才能生效。
$('#select').val(custom).change();
我发现了如何完成我想要的。解决方案是...
$('#select').select2('data', {id: id, text: custom});
以下将设置输入为 custom
的任何值,而不添加到列表本身。
这是一个有效的 fiddle。
我实现了一个 select2
下拉列表,允许用户输入自定义输入...
$("#select").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
multiple: false,
selectOnBlur: true,
data: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
});
这很好用,但在某些情况下,我需要以编程方式为 select2
下拉列表设置自定义值。我尝试执行以下操作...
// Doesn't work
$('#select').val('val', custom);
// Doesn't work
$('#select').val(custom);
有什么办法吗?
正在处理 fiddle 我的 select 下拉菜单。
是否要显示所选值?如果是这样你可以添加
$('#select').val(custom).attr("selected", "selected").change();
如果我没记错的话,你需要触发select2的更改才能生效。
$('#select').val(custom).change();
我发现了如何完成我想要的。解决方案是...
$('#select').select2('data', {id: id, text: custom});
以下将设置输入为 custom
的任何值,而不添加到列表本身。
这是一个有效的 fiddle。