Reordering <option>'s after <select> has been rendered
HTML
<select name="ShippingMethod">
<option value="3">(40.51%)</option>
<option value="1">(10.00%)</option>
<option value="1">(20.00%)</option>
<option value="1">(2.00%)</option>
<option value="1">(40.50%) Asd</option>
<option value="1">(50.00%)</option>
<option value="1">(60.00%)</option>
<option value="0">(90.20%) ABV</option>
<option value="2">(90.20%) HAaA</option>
<option value="8">(0.10%)</option>
</select>
JavaScript
var shippingOptions = [];
var getPriceList = function () {
var prices = [];
// Get the price in the option
var getPrice = function (str) {
var price = 0;
var result = str.match(/[0-9]+(.)[0-9]{2}/); //regex matches >1 digit followed by . decimal, followed by 2 digits
if (result.length > 0) {
price = parseFloat(result[0]);
}
return price;
};
// Sort the prices
var sortPrices = function (priceList) {
priceList.sort(function (a, b) {
return a.price > b.price; // > is sort ascending order
});
return priceList;
};
// Get the option's label, value, price
$('select[name=ShippingMethod] option').each(function () {
var option = $(this);
var price = getPrice(option.text());
prices.push({
label: option.html(),
value: option.val(),
price: price
});
});
prices = sortPrices(prices);
return prices;
};
shippingOptions = getPriceList();
// create output HTML
var output = '';
for (var i = 0; i < shippingOptions.length; i++) {
output += '<option value="' + shippingOptions[i].value + '">' + shippingOptions[i].label + '</option>';
}
// replace select with sorted options
$('select[name="ShippingMethod"]').html(output);