javascript - 如何使用自定义输入填充 select2
问题描述
我实现了一个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);
有没有办法做到这一点?
我的选择下拉列表的工作小提琴。
解决方案
我发现了如何完成我想要的。解决方案是...
$('#select').select2('data', {id: id, text: custom});
以下将输入设置为任何值custom
而不添加到列表本身。
这是一个工作小提琴。
推荐阅读
- android - 关于 super.onBackPressed() 动画展示
- mysql - Flask,试图从 mysql db 中读取数据(并非所有参数都在字符串格式化期间转换)
- vuejs2 - Vuejs - 外部路由文件
- ruby - 意外的 Ruby 正则表达式行为
- android - 通过更多参数反应原生过滤器 json 对象
- javascript - 如何通过 this.props.children() 而不是 this.props.children 传递道具
- ios - 仅将角半径应用于顶部和底部单元时面临设计问题
- typo3 - TYPO3 在流体中裁剪图像
- c# - 为记录套接字通信创建一个高效的日志库
- javascript - 显示不同的图标,如果数字是 1 或 0 - ASP.NET C# MVC JQuery