Reputation: 1098
I'm trying to use jQuery plugin "Chosen"
(http://harvesthq.github.com/chosen/ and https://github.com/harvesthq/chosen)
in my project.
What I'm trying to achieve is update list basing on user selection (ajax
call (tree based structure
))
This is no bigger problem, because i can use .chosen().change(function())
and remove all unused select items and then .append new ones.
Then I can use .trigger("liszt:updated")
to update list, but unfortunately all selections are deleted..
Does anyone know a way how to update chosen list without loosing selected data?
In theory I can manually remove all chosen generated
Upvotes: 4
Views: 14056
Reputation: 855
This will reload the selection after xhr request (refresh list) and delete the selection if the new item list not contains the earlier selected item:
var chosenSelectedItems = $(".chosen-select").val();
$('select#GroupsStr').empty();
$.each(xhr.ReturnValue, function (index, item) {
var newOption = $('<option value="' + index + '">' + item + '</option>');
$('select#GroupsStr').append(newOption);
});
$("select#GroupsStr").val(chosenSelectedItems).trigger("chosen:updated");
Upvotes: 1
Reputation: 11726
The new code now updates the list without losing the selections, and it sorts the selections based on the options order.
$('.chosen-select').trigger('chosen:updated');
Reference their project page.
Upvotes: 1
Reputation: 789
This should be fairly simply if you save the items selected. For example:
<select data-placeholder="Choose a country..." style="width:350px;" multiple="true" class="chosen-select">
$(".chosen-select").chosen();
Now, before updating the chosen, make sure you save the items selected like this:
var chosenSelectedItems = $(".chosen-select").val(); // this gets you the select value data
// Update the select items
$('.chosen-select').trigger('liszt:updated');
$(".chosen-select").val(chosenSelectedItems);
This should be able to reset the original values before the change.
Upvotes: 6
Reputation: 3979
I have created a few cascading or dependent dropdowns using chosen, but I have used them in addition to knockoutjs. KnockoutJS is used for binding data (in your case the select) to an object and a DOM element. Knockout also allows you to create custom bindings to handle things they may not have anticipated straight out of the box. With that being said I created a custom binding for knockout that utilized Chosen and it turned out well...
In our case we allow users to select a channel (using chosen) we then load in their locations (either by displaying or creating another select element) and trigger our custom binding which will update the data and trigger our custom binding that will tell chosen to run .trigger("liszt:updated")
but keep the data in the background.
Our code is rather proprietary and I don't know that it would necessarily show you easily how to achieve this, but perhaps this will give you another way of looking at it.
Upvotes: 0