Bootstrap select picker automatically sorting based on key

Govinda Sakhare picture Govinda Sakhare · Aug 22, 2016 · Viewed 9.3k times · Source

I am using Bootstrap selectpicker for populating the select box.

I have the data in the DB table like this,

*cId*  *CountryName*
1      Australia
2      Belgium
3      Canada
4      India
5      Zimbabwe
6      Brazil

What I am doing is ordering the data based on countryName and populating cId as option element's key and countryName as option element's value

function loadJSONtoSelectBox(selector, options)
{
   $(selector).selectpicker();
   $.each(options, function(key, value) {
       $('<option data-tokens="'+value+'" value="' + key + '">' + value + '</option>').appendTo(selector);
       $(selector).focus();
  });

  $(selector).selectpicker('refresh');
}

But internally it is sorting based on option's value attribute i.e it is showing Brazil(cid is 6) at the end instead of after Belgium, what is the hack to solve this issue? how can I turn off that internal sorting?

Fiddle link https://jsfiddle.net/14a3h2bt/

For more reference check my comment here: https://github.com/silviomoreto/bootstrap-select/issues/1476

Answer

Vimal Raiyani picture Vimal Raiyani · Sep 1, 2016

I have just wrote some JavaScript for your solution.

For this we can do like sorting things. So i was sorting your content alphabetical.

Please take a look in Fiddle. Hope it will help you. :)


$(document).ready(function() {
  var options = $('.dropdown-menu .text');
  var arr = options.map(function(_, o) {
    return {
      t: $(o).text(),
      v: o.value
    };
  }).get();
  arr.sort(function(o1, o2) {
    return o1.t.toUpperCase() > o2.t.toUpperCase() ? 1 : o1.t.toUpperCase() < o2.t.toUpperCase() ? -1 : 0;
  });
  options.each(function(i, o) {
    o.value = arr[i].v;
    $(o).text(arr[i].t);
  });
});