1

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!

1

2 Answers 2

1

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
}));
0

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"">

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.