1

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>
amphetamachine
  • 27,620
  • 12
  • 60
  • 72

2 Answers2

1

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.

0

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/

Community
  • 1
  • 1