3

I have a select box that dynamically shows a list of shipping options and prices. I want them to be in order from lowest to highest price.

Here's example html.

<select name="ShippingMethod">
  <option value="ups:1">UPS Next Day Air ($30.08)</option>
  <option value="ups:4">UPS 2nd Day Air ($14.77)</option>
  <option value="ups:6">UPS 3 Day Select ($10.93)</option>
  <option value="ups:7">UPS Ground ($8.00)</option>
  <option value="flatzonc:Pick up in store">Pick up in store ($0.00)</option>
  <option value="mvusps:PRIORITY">U.S.P.S. Priority Mail&reg; ($7.45)</option>
</select>

I know how to put the values into an array with this:

shippingOptions = [];
$('select[name=ShippingMethod] option').each(function() {
    myList.push($(this).html())
});

but thats as far as I got. I don't know how to use that to sort them and reinsert them in order. I'm new to javascript so I appriciate the help.

Thanks

4

4 回答 4

3

http://jsfiddle.net/hPZ3F/17

// get all options
var shippingOptions = $('select[name=ShippingMethod] option');

// initialize sort
shippingOptions.sort(function(a,b) {
    // define regex that pulls contents of parens
    var patt = /\((.*)\)/;

    // for each element in sort, find the price and remove the dollar sign
    a.price = a.text.match(patt)[1].replace('\$', '');
    b.price = b.text.match(patt)[1].replace('\$', '');

    return a.price - b.price;
});

// update the select with the new option order
$('select[name=ShippingMethod]').append(shippingOptions);

// select the first option
$(shippingOptions[0]).attr("selected", "");
于 2013-03-21T19:07:04.560 回答
3

首先,您需要提取每个选项的 $ 金额,然后对它们进行排序并替换现有的下拉列表,这是完整的代码:

http://jsfiddle.net/amyamy86/L8qgX/

// 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;
    };

var prices = [];
// 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
        });
    });

var shippingOptions = sortPrices(prices);

// 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);

您可以了解有关使用的更多信息:

于 2013-03-21T19:25:28.343 回答
2

嗯,已经回答了,但我已经写了这个,所以无论如何我都会发布,这几乎是所有其他内容的混合,哈哈..

$('select[name=ShippingMethod]').
    html($('select[name=ShippingMethod] option').
         clone().sort(function (a, b) {
            a = a.innerHTML, b = b.innerHTML;
            return parseFloat(
                    a.substr(a.indexOf('$') + 1)
                ) >= parseFloat(
                    b.substr(b.indexOf('$') + 1)
                );
        })
    );

http://jsfiddle.net/6zbzK/

编辑:查看评论后,这是一个更有效但更详细的答案:

var selectOpts = $('select[name="ShippingMethod"] option');
var len = selectOpts.length;
var options = new Array(len), out = "", i;
selectOpts.each(function (index) {
    var self = $(this);
    var txt = self.text();
    options.push({
        'html': '<option value="' + self.val() + '">' + txt + '</option>',
        'price': parseFloat(txt.substr(txt.indexOf('$') + 1))
    });
    // Return if not last item
    if (index !== len - 1) {
        return;
    }
    // Sort options and set 'out'
    options.sort(function (a, b) {
        return a.price > b.price;
    });
    for (i = 0; i < len; i += 1) {
        out += options[i].html;
    };
}).parent('select').html(out);

http://jsfiddle.net/QnHFH/

于 2013-03-21T19:36:16.903 回答
1

Try this.. Here Sorting is done on value.. You can use .text to sort based on text

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

Demo

Sort on text: Demo 2

 return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 ;

Sort on values indside braces in text : Demo 3

$("select").html($("select option").sort(function (a, b) {
    var a1 =  parseFloat(a.text.match(/\(.*?([\d.]+).*?\)/)[1].replace("$",""));
    var b1 =  parseFloat(b.text.match(/\(.*?([\d.]+).*?\)/)[1].replace("$",""));
    return a.text == b.text ? 0 : a1 < b1 ? -1 : 1
}));
于 2013-03-21T18:50:05.563 回答