javascript - Bootstrap 选择可编辑组合框黑客
问题描述
如何让我的用户将自己的选项添加到 bootstrap-select?
你好。在花了一些时间试图找到一个适用于 bootstrap 4 样式的简单解决方案之后,包括查看提供的解决方案和等待这个未解决问题的死线程:https ://github.com/snapappointments/bootstrap-select/issues/990 ,我决定自己动手。
以下解决方案依赖于在 bootstrap-select 元素上启用的实时搜索选项。它使用实时搜索字段将用户键入的自定义值添加到选项列表中。这是一个 hacky 解决方案,而不是最漂亮的东西,但也许这个概念可以直接集成到 bootstrap select 中,最终解决问题 990。
解决方案
让用户将自己的值添加到具有引导选择实时搜索功能的选择器中
只需将此代码添加到您的页面。将(yourselector)替换为您的选择器。对于我的项目,我只想要任何不具备多重功能的 selectpicker 元素,所以我使用了 .selectpicker:not([multiple])。
var newOption;
$(document).ready(function () {
//Custom editable combobox
$(document).on("loaded.bs.select", "(yourselector)", function (e, clickedIndex, isSelected, previousValue) {
newOption = ""; //Reset newOption before doing a new search
$(e.currentTarget).siblings(".dropdown-menu").on('keyup', '.bs-searchbox input', function (ie) {
//if more than one and search is 0 characters, continue. If more than one and search is 1 character and character doesn't match first character of newValue, delete newValue.
//If 1 and class is "no-results", delete old newValue and add newValue.
console.log("running keyup script for " + e.currentTarget.id);
var searchList = $(e.currentTarget).siblings("div.dropdown-menu ul.dropdown-menu li");
var searchPhrase = $(ie.currentTarget).val();
//Something was found
if (searchList.length > 0 && !$(searchList[0]).hasClass("no-results")) {
//new search
if (searchPhrase.length == 0)
return;
else {
//they haven't started searching the same phrase again
if (newOption && newOption.toLowerCase().indexOf(searchPhrase.toLowerCase()) < 0) {
console.log("newOption: " + newOption + "\nsearchPhrase: " + searchPhrase + "\nSubstring?: " + newOption.toLowerCase().indexOf(searchPhrase.toLowerCase()));
//delete newOption from options list and reset
$("#" + e.currentTarget.id + " option[value='" + newOption + "']").remove();
newOption = "";
$(e.currentTarget).selectpicker("refresh");
$(ie.currentTarget).trigger('propertychange');
}
}
}
//Nothing was found
else {
$("#" + e.currentTarget.id + " option[value='" + newOption + "']").remove();
newOption = searchPhrase;
$(e.currentTarget).append($('<option>').val(searchPhrase).text(searchPhrase));
$(e.currentTarget).selectpicker("refresh");
$(ie.currentTarget).trigger('propertychange');
}
})
});
$(".selectpicker").on("changed.bs.select", function (e, clickedIndex, newValue, oldValue) {
newOption = ""; //Reset newOption before doing a new search
});
});
推荐阅读
- node.js - 如何通过 puppeteer 拦截网站客户端生成的 blob 下载?
- cmake - CMake从生成器表达式中删除转义字符
- javascript - 不能在回调中调用 React Hook “useState”
- sql-server - 使 SSAS 模型保持最新的方法?
- c# - 当 Transfer-Encoding = chunked 时,如何增加可以部分请求的范围限制?
- excel - Excel 数据透视表中的相同/重复列名
- python-3.x - 如何将 .txt 文件中的字符串拆分为列表,从 AZ 排序且不重复?
- visual-studio - 如何使用 ifort 编译器运行 fortran 程序?
- java - Twitter4j 搜索
- ansible - Ansible Json字符串如何使用json_query从json获取价值