jQuery Chosen - update select list without losing selections

前端 未结 4 953
梦如初夏
梦如初夏 2021-01-13 19:36

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

相关标签:
4条回答
  • 2021-01-13 20:24

    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.

    0 讨论(0)
  • 2021-01-13 20:27

    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.

    0 讨论(0)
  • 2021-01-13 20:30

    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");
    
    0 讨论(0)
  • 2021-01-13 20:37

    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.

    0 讨论(0)
提交回复
热议问题