ShaneH
ShaneH

Reputation: 385

Change the order in a jquery populated form select

I've built a dynamically populated multiselect form for my site. When the user selects one or more items in the first select, the second is filled via jQuery. The form works correctly except for the order the multiselect is filled.

e.g. The "product" select contains:

<select name="product_id" id="products" multiple="multiple">
<option value="#" selected="selected">Please Select</option>
<option value="1">Product 1</option>
<option value="5">Product 2</option>
<option value="4">Product 3</option>
<option value="6">Product 4</option>

(Yes, the values are not the same as the product numbers) When a user selects one of these the jQuery call populates the next dropdown.

<select name="version_id" id="versions" multiple="multiple">
<option value="100">3.0.7</option>
<option value="101">1.0.8</option>
<option value="102">12.0.1</option>

The code fills this select and orders by "value", is there a way to force it to order by the actual content e.g. change it to:

<option value="101">1.0.8</option>
<option value="100">3.0.7</option>
<option value="102">12.0.1</option>

The success code in my call is:

success: function(versions) 
{
$.each(versions,function(id,version) 
{
var opt = $('<option />'); 
opt.val(id);
opt.text(version);
$('#versions').append(opt); 
});
}

Thanks!

Upvotes: 1

Views: 824

Answers (2)

ShaneH
ShaneH

Reputation: 385

Thanks to @deifwud for pointing me in the right direction. In the end I added the following directly after my success function. It re-orders the results sorting by the text instead of the value.

$("#versions").html($("#versions option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));

Upvotes: 1

OM The Eternity
OM The Eternity

Reputation: 16234

you must be doing a ajax call to a file where a sql query is executed to dynamically generate the next dropdown box.... if this is the case then you need to place the keyword "ASC" at the last of select query which is yielding your "id" in value attribute of <option value"">

Upvotes: 0

Related Questions