aspirinemaga
aspirinemaga

Reputation: 3947

Reorder the options in a SELECT list with jQuery

Any suggestion how to resort/reorder the <option> elements inside that <select> ? Here is the html:

<select class="required" name="jform[params][language]" id="jform_params_language">
    <option value="cs-CZ">Czech (Cestina)</option>
    <option value="en-GB">English (United Kingdom)</option>
    <option value="sk-SK">Slovak (Slovencina)</option>
</select>

I need it to be in this way:

<select class="required" name="jform[params][language]" id="jform_params_language">
    <option value="sk-SK">Slovak (Slovencina)</option>
    <option value="en-GB">English (United Kingdom)</option>
    <option value="cs-CZ">Czech (Cestina)</option>
</select>

Need to mention that i can't modify the html. I tried to use jQuery's sort() function but do not know how to do it.

Upvotes: 6

Views: 10481

Answers (2)

Kheteswar
Kheteswar

Reputation: 191

E.g. to move 3rd option before 1st option, we can use below jquery:

$('select[name="NameOfDropDown"] option:eq(2)').insertBefore($('select[name="NameOfDropDown"] option:eq(0)'));

Upvotes: 7

Ram
Ram

Reputation: 144729

You can use reverse method.

var $sel = $('#jform_params_language'),
    $o = $sel.children().toArray().reverse();

$sel.append($o); //[0].selectedIndex = 0;

http://jsfiddle.net/3UWx6/

Upvotes: 9

Related Questions