我正在使用
the chosen plugin.
将其添加到我的文档不能使我键入文本字段并添加一个新项目到列表.
$(document).ready(function (){
$(".chosen-select").trigger("chosen:updated");
});
这将允许将一些硬编码的文本添加到列表中:
$(document).ready(function (){
$('.chosen-select').chosen();
$('.addsomething').click(function (){
$(".chosen-select").prepend("<option>utopia</option>");
$(".chosen-select").trigger("chosen:updated");
});
});
我想看到的是,我希望能够在文本字段中添加文本,点击返回,如果我没有选择它,则添加我的条目.它不需要永久添加到选项列表.
解决方法
不知道是否可以以更简单的方式完成,但是这样做很好.代码的意见解释了每一步:
var select,chosen;
// Cache the select element as we'll be using it a few times
select = $(".chosen-select");
// Init the chosen plugin
select.chosen({ no_results_text: 'Press Enter to add new entry:' });
// Get the chosen object
chosen = select.data('chosen');
// Bind the keyup event to the search Box input
chosen.dropdown.find('input').on('keyup',function(e)
{
// If we hit Enter and the results list is empty (no matches) add the option
if (e.which == 13 && chosen.dropdown.find('li.no-results').length > 0)
{
var option = $("<option>").val(this.value).text(this.value);
// Add the new option
select.prepend(option);
// Automatically select it
select.find(option).prop('selected',true);
// Trigger the update
select.trigger("chosen:updated");
}
});
这是一个工作示例:http://jsfiddle.net/jHvmg/436/