Im trying to build my dropdown menu using the plugin Chosen for Multiple Select . Here's to behavior I'm based on:
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.
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"}]
The code:
$(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>');
}
});
}
});
Result:
I type "car", in the dropdown Im getting "No result for car" and then I have all my results, as I want.
1. Why I'm I getting the "No result" message, cause I can see in my json array and inside my list that I'm getting results.
-----------------------------
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. Im I suppose to clear the ul on keyUp?? Thought the plugin was doing that already
-----------------------------
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 is undefined
"item.selected = true;" line 732
the link to the plugin: http://harvesthq.github.com/chosen/chosen/chosen.jquery.js
and it's not adding anything inside the select.
3. No idea why this is happening
-----------------------------
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....
You can dynamically populate a list via AJAX using the excellent Select2 plugin. From my answer to "Is there a way to dynamically ajax add elements through jquery chosen plugin?":
Take a look at the neat Select2 plugin, which is based on Chosen itself and supports remote data sources (aka AJAX data) and infinite scrolling.