-1

I have this dropdown list, but the options are not set in the correct order. Is there a way to sort them (based on their value i guess) using javascript?

<select class="required" name="payment_gateway">
<option value="bank-transfer">Bank</option>
<option value="pay-social">Social</option>
<option value="paypal">PayPal</option>
<option value="pronamic_ideal">iDEAL</option>
</select>

The desired sorting would be:

<select class="required" name="payment_gateway">
<option value="pay-social">Social</option>
<option value="pronamic_ideal">iDEAL</option>
<option value="bank-transfer">Bank</option>
<option value="paypal">PayPal</option>
</select>
RobbertT
  • 253
  • 2
  • 5
  • 14
  • I strongly recommend jQuery, if you can't, take a look in the second answer: http://stackoverflow.com/questions/667010/sorting-dropdown-list-using-javascript – Kriggs Aug 26 '15 at 11:58
  • 1
    possible duplicate of [sort select menu alphabetically?](http://stackoverflow.com/questions/5248189/sort-select-menu-alphabetically) – Shailendra Sharma Aug 26 '15 at 11:59
  • actually i would like the 'pay-social' to be the first option. – RobbertT Aug 26 '15 at 12:00
  • on what condition would you like to order the list? custom or for instance alphabetically? – kumaheiyama Aug 26 '15 at 12:03
  • There isn't enough information to help here. How are you currently outputting the select options? It's not clear that you couldn't just re-order your HTML. – duncanhall Aug 26 '15 at 12:04
  • The desired order is given. The list is now populated through php and it would require editing the core files in order to change the sorting. Thats why i was hoping that sorting through javascript/jquery would be possible. – RobbertT Aug 26 '15 at 12:07

3 Answers3

0

Try to write so

var $dropdown = $('.required'),
    $items = $dropdown.children('option');


$items.sort(function(a, b){
    var an = a.value,
        bn = b.value;
    if (an > bn) {
        return 1;
    }
    if (an < bn) {
        return -1;
    }
    return 0;
});
$items.detach().appendTo($dropdown);
  • Hi,Thanks a lot for your response. This is not changing the order however. Everything stays the same. – RobbertT Aug 26 '15 at 12:32
0

This seems to be working, however the wrong option is still selected.

$('.required option[value="pay-social"]').insertBefore('.required option[value="bank-transfer"]');
RobbertT
  • 253
  • 2
  • 5
  • 14
0

Here a working example

<select class="required" name="payment_gateway"><option value="pay-social">Social</option><option value="pronamic_ideal">iDEAL</option><option value="bank-transfer">Bank</option><option value="paypal">PayPal</option></select>

http://jsfiddle.net/snayps/tdh9up7h/

  • thannks, but Im not sure what you mean. In the fiddle example the options are already sorted in html.. – RobbertT Aug 26 '15 at 13:05