Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Chosen - update select list without losing selections

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

  • elements and then populate with new ones, but then is a problem with getting SELECT "value" data.
  • like image 695
    PsychoX Avatar asked Feb 22 '23 08:02

    PsychoX


    2 Answers

    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.

    like image 96
    Anshuman Biswas Avatar answered Mar 08 '23 13:03

    Anshuman Biswas


    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.

    like image 31
    konyak Avatar answered Mar 08 '23 14:03

    konyak