我正在尝试使用出色的 Select2 以编程方式清除下拉列表图书馆。下拉列表使用 Select2 query
选项动态填充远程 ajax 调用。
HTML:
<input id="remote" type="hidden" data-placeholder="Choose Something" />
Javascript:
var $remote = $('#remote');
$remote.select2({
allowClear: true,
minimumInputLength: 2,
query: function(options){
$.ajax({
dataType: 'json',
url: myURL + options.term,
error: function(jqXHR, textStatus, errorThrown){
smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
},
success: function(data, textStatus, jqXHR){
var results = [];
for(var i = 0; i < data.length; ++i){
results.push({id: data[i].id, text: data[i].name});
}
options.callback({results: results, more: false});
}
});
}
});
不幸的是,调用 $remove.select2('val', '')
会抛出以下异常:
Uncaught Error: cannot call val() if initSelection() is not defined
我试过设置 attr
、设置 val
、text
和 Select2 特定的 data
函数.似乎无法让这个人清楚并以单选按钮的方式工作。有人有建议吗?
最佳答案
这对我有用:
$remote.select2('data', {id: null, text: null})
当您以这种方式清除它时,它也可以与 jQuery validate 一起使用。
-- 编辑 2013-04-09
在撰写此回复时,这是唯一的方法。通过最近的补丁,现在可以使用一种正确且更好的方法。
$remote.select2('data', null)
关于javascript - 使用 jQuery Select2 清除下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240047/