Jquery Chosen插件 - 由Ajax动态填充列表 [英] Jquery Chosen plugin - dynamically populate list by Ajax
问题描述
我正在尝试使用选择多选的插件来构建我的下拉菜单。
这是基于我的行为:
Im trying to build my dropdown menu using the plugin Chosen for Multiple Select . Here's to behavior I'm based on:
所以,而不是有3个harcoded<选项>在我的选择中。我希望此列表是由ajax请求填充的json数组的值。这将由自动完成触发。
So, instead of having 3 harcoded < option > in my select. I want this list to be the values of a json array populated by an ajax request. This will be triggered by autocomplete.
因此,如果用户输入car,即可通过ajax调用发送信件,并且即时取回类似的数组:
So, if the user type "car", im sending the letter via an ajax call, and im getting back an array like that:
[{id:2489,name:carrie},{id:2490,name:Caroline },{id:2491,name:Carole}]
[{"id":"2489","name":"carrie"},{"id":"2490","name":"Caroline"},{"id":"2491","name":"Carole"}]
代码:
$(function() {
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({allow_single_deselect:true});
$('.chzn-choices input').autocomplete({
source: function( request, response ) {
$.ajax({
url: "/change/name/autocomplete/"+request.term+"/",
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
$('ul.chzn-results').append('<li class="active-result">' + item.name + '</li>');
}
});
}
});
结果:
我输入car,在下拉列表中我得到没有汽车的结果,然后我得到了我想要的所有结果。
I type "car", in the dropdown Im getting "No result for car" and then I have all my results, as I want.
1。为什么我收到无结果消息,因为我可以在我的json数组中看到我的列表中我得到的结果。
-----------------------------
当我删除car并输入sam时。在汽车结果之后显示sam的结果。 (基本上,我看到两者的结果,而不仅仅是我当前搜索的结果)
When I delete "car" and enter "sam". The results for "sam" are showing after the "car" results. (Basically, I see the result for both, instead of just having the result of my current search)
2。我想我要清除keyUp上的ul?以为插件已经这样做了
-----------------------------
当我点击名称时实际选择它并将其添加到选择中,我在selected.js文件中得到一个javascript错误
When I click on a name to actually select it and add it into the select, Im getting a javascript error inside the chosen.js file
项目未定义
item.selected =真; 732行
item is undefined
"item.selected = true;" line 732
插件的链接:
http://harvesthq.github.com/chosen/chosen/chosen.jquery.js
并且它没有添加选择内的任何内容。
and it's not adding anything inside the select.
3。不知道为什么会发生这种情况
-----------------------------
你们有什么想法我做错了什么?我完全被困在这里......!
Do you guys have any idea on what I'm I doing something wrong? I'm completly stuck here...!
哦顺便说一句,我不介意更改插件源,因为它是我使用它的唯一地方....
Oh and by the way, I dont mind changing the plugin source, as it's the only place where I'm using it....
推荐答案
试试这个:
$('.chzn-choices input').autocomplete({
source: function( request, response ) {
$.ajax({
url: "/change/name/autocomplete/"+request.term+"/",
dataType: "json",
beforeSend: function(){$('ul.chzn-results').empty();},
success: function( data ) {
response( $.map( data, function( item ) {
$('ul.chzn-results').append('<li class="active-result">' + item.name + '</li>');
}));
}
});
}
});
这篇关于Jquery Chosen插件 - 由Ajax动态填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!