2

I am using Chosen jquery library. The values selected are stored in an array and then loaded again later on. The values that get loaded are correct, but the order of selection is incorrect.
For example, if i selection option3 and then option2, the order is option2, option3 when reloaded.
html:

<select id="second" data-placeholder="Choose a Country..." class="chosen-select" multiple style="width:350px;" tabindex="4">    
     <option value=""></option> 
     <option value="United States">United States</option>
     <option value="United Kingdom">United Kingdom</option> 
     <option value="Afghanistan">Afghanistan</option> 
     <option value="Albania">Albania</option> 
     <option value="Algeria">Algeria</option> 
     <option value="American Samoa">American Samoa</option> 
     <option value="Andorra">Andorra</option> 
     <option value="Angola">Angola</option> 
     <option value="Anguilla">Anguilla</option>
</select>

JavaScript:

$(".chosen-select").chosen();
var selectedOptions = [];
$('button').click(function(){
    //$(".chosen-select").val('').trigger("chosen:updated");
  $('#second_chosen ul li span').each(function(i, selected){
      selectedOptions[i] = $(selected).text();
  });
  //clear the selection
  $("#second").val("").trigger("chosen:updated");

});

$('#previousBtn').click(function(){
    console.log(selectedOptions);
    $("#second").val(selectedOptions).trigger("chosen:updated");
});


The order of selection is correct in selectedOptions array, but it displays in the order of the options, instead of order of selection.
Please find jsfiddle: https://jsfiddle.net/Da4m3/1051/.
Any idea how this can be fixed?

Bharata
  • 13,509
  • 6
  • 36
  • 50
Aswathy
  • 63
  • 6

3 Answers3

0

I used push() function to add values to selectedOptions array

$('#second_chosen ul li span').each(function(i, selected){
    selectedOptions.push($(selected).text());
});

https://jsfiddle.net/Da4m3/1096/

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
Albert
  • 90
  • 2
  • 9
0

the point is, the entries in array are not shown in the same order in the select

Shakti
  • 5
  • 1
  • 3
0

See if the below link helps.

Chosen: Keep Multiple Selection Order

https://github.com/tristanjahier/chosen-order

There is a plugin for what you are asking.

Niragh
  • 162
  • 2
  • 10