Terry Whatevering
Terry Whatevering

Reputation: 13

Bootstrap Select List

I need to sort this dropdown selector by alphabetical letters

<div class="container">
  <form role="form">
    <div class="form-group">
      <select class="form-control" >
<option value="1">a</option>
<option value="2">d</option>
<option value="3">b</option>
<option value="4">c</option>
</select>
    </div>
  </form>
</div>

Upvotes: 1

Views: 2202

Answers (2)

user2346766
user2346766

Reputation:

This Codepen might be just what you are looking for.

Note: it requires jQuery. Put <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

In the head of your page.

Upvotes: 1

Gregory Wullimann
Gregory Wullimann

Reputation: 567

You need some javascript code, here is "my" solution, this is done with jQuery.

var items = $('#select option').get();
items.sort(function(a,b){
  var keyA = $(a).text();
  var keyB = $(b).text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var select = $('#select');
$.each(items, function(i, option){
select.append(option);
});

And you should add an ID (or class, or something) to the <select>

 <select id="select" class="form-control" >

Source: What is the easiest way to order a <UL>/<OL> in jQuery?

JSFiddle: https://jsfiddle.net/rbe2e665/

Upvotes: 0

Related Questions