Jake Jake - 10 months ago 92
jQuery Question

Restore pre-selected values in Chosen Select

In the fiddle attached, I have two options pre-filled "Denmark" and "France", when the chosen select loads. If I select more values in the select box and click the clear button, I would like to restore the chosen select with the same pre-filled values "Denmark" and "France".

I would like to change this code to prefill selected values.

$("#Clear").click(function () {
$('.chosen-select option').prop('selected', false).trigger('chosen:updated');



What you need is to create an array of pre-selected option's value. Then you can use a forEach loop with this array to change the value of selected and get the initial state before trigger update.


let preselected = [];

$('[selected]').each((i, node) =>{

$("#Clear").click(function () {
    $('.chosen-select option').prop('selected', false);

    preselected.forEach(pre => {
        $("option[value='" + pre + "']").attr('selected', 'selected');

    $('.chosen-select option').trigger('chosen:updated');