使用javascript对选择框中的选项重新排序

时间:2013-03-21 18:48:53

标签: javascript jquery html forms

我有一个选择框,可以动态显示送货选项和价格列表。我希望它们从最低价到最高价。

这是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>

我知道如何将值放入数组中:

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

但就我而言。我不知道如何使用它来排序它们并按顺序重新插入它们。我是javascript的新手,所以我赞成了帮助。

由于

4 个答案:

答案 0 :(得分: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", "");

答案 1 :(得分:3)

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

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

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

答案 2 :(得分: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/

答案 3 :(得分:1)

试试这个..这里排序是在值上完成的..您可以使用.text根据文本进行排序

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

Demo

按文字排序:Demo 2

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

对文字中的大括号进行排序: 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
}));