Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Reorder select options with jQuery WordPress

  • SOLVED

I need to reorder the options that appear in a drop down select field, hopefully using jQuery.

For several reasons, I am unable to reorder the options manually, so can I do it with jQuery?

I have something like this:

- select
- option 1
- option 2
- option 3

and I need it to be:

- select
- option 3
- option 1
- option 2

Or any variation in between.

Answers (2)

2010-12-17

Peter Michael answers:

See [[LINK href="http://stackoverflow.com/questions/660572/how-would-you-dynamically-order-an-option-select-list-using-jquery"]]http://stackoverflow.com/questions/660572/how-would-you-dynamically-order-an-option-select-list-using-jquery[[/LINK]]

2010-12-17

Jonah Schulte answers:

One way to do it is to remove the existing options and add different ones:



<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>

<select id="test">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

<script type="text/javascript">

$(document).ready(function(){

// Clear the existing options
$("select#test option").remove();

// These are the new options we will set
var testOptions = {
'option1' : 'Option 1',
'option3' : 'Option 3',
'option2' : 'Option 2'
};

// Add the new options to the select list
$.each(testOptions, function(val, text) {
$('select#test').append(
$('<option></option>').val(val).html(text)
);
});
});

</script>
</body>
</html>