我尝试了这里和其他地方给出的几种解决方案,但是没有一个在 selected.js 1.8.5 (jQuery: 3.3.1) 中有效,所以我最终得到了以下内容,因为我不想使用可能并不总是启动的 fork -to-date 到 master 分支:
对于我可能不希望任何.chosen-select
允许新值的情况,我添加了一个新类.chosen-newValuesAllowed
。我在这个类上设置了一个事件处理程序,如果新值不存在, CTRL + 我会添加它。之后输入字段上的焦点不会丢失。在我的示例中,我检查了innerHTML,因为@value 实际上包含数据库ID,因此新值(在我的示例中是稍后将由服务器处理的字符串)永远无法在@value 中找到。如果您想检查@value,请查看代码段内的注释。该代码处理单选和多选。
$(document).on("keydown", ".chosen-container.chosen-newValuesAllowed input", function(e) {
if (e.ctrlKey === true && e.keyCode === 73) { // CTRL + I
e.preventDefault();
var newValue = $(this).val();
if (newValue) {
try {
// only add if there is no option having the content/text of "input" yet!
// instead of filter() for the content of <option> you can check on its @value by: find("option[val='...']")
var $selectElement = $(e.target).closest("div.chosen-container").prev(); // the previous sibling should be the <select>. If not, grab it some other way, e.g. via @id
if (!$selectElement.find("option").filter(function () { return $(this).html() === newValue; }).length) {
if (!$selectElement.attr("multiple")) { // unselect for single-select
$selectElement.val('');
}
$selectElement.append('<option val="' + newValue + '" selected>' + newValue + '</option>');
$selectElement.trigger('chosen:updated');
}
} catch(error) {
// pass
}
e.target.focus();
}
return false;
}
});
另一种解决方案是调用可触发函数selected:no_results如果仅在明确没有结果的情况下才应添加新值:
$(".chosen-select.chosen-newValuesAllowed").on("chosen:no_results", function(e, data){
var newValue = data.chosen.get_search_text();
...
});