I am trying to integrate jquery-chosen jquery-chosen into my application.
I have two select controls: when a user selects an option from the first one, the second one updates dynamically (through jQuery) according to the value selected from the first one (classic cascading selects).
It is in the second select control that I wish to use jquery-chosen.
Here is my js:
$(document).ready(function() {
$(".chzn-select").chosen();
});
$(document).ready(function() {
var geolocationRegionSelect = $("#geolocationRegionSelect");//first select control
geolocationRegionSelect.bind('change', function(event) {
$.get("/kadjoukor/geolocations/findDepartmentsByRegion?regionId="+$(this).val(), function(result){
console.log(result);
var geolocationDepartmentSelect = $("#geolocationDepartmentSelect");//second select control
geolocationDepartmentSelect.empty();
$.each(result, function() {
geolocationDepartmentSelect.append($("<option />").val(this.id).text(this.department));
});
}, 'json');
$("#geolocationDepartmentSelect").trigger("liszt:updated");
});
});
Here is the html for the second control:
<div class="controls">
<select id="geolocationDepartmentSelect" data-placeholder="Choose a department" multiple="multiple" class="chzn-select chzn-done"></select>
</div>
I noticed that using jquery-chosen on a statically populated select works fine. It is only with my dynamically populated select (the second one) that I can’t get jquery-chosen to work.
I tried to use the trigger function as documented in the jq-chosen page:
Updating Chosen Dynamically
If you need to update the options in your
select field and want Chosen to pick up the changes, you’ll need to
trigger the "liszt:updated" event on the field. Chosen will re-build
itself based on the updated content.
It does not work for me unfortunately…
EDIT: I must also mention that the chosen control just renders as a plain html multiple select when the page is loaded.
I changed the select control to:
and the js to:
and
and the issue is gone.