Christopher
Christopher

Reputation: 610

Sort drop down options

I am trying this solution to sort out a drop down menu but having two digits in the options, 14 and 11 comes before 8 and 9.

How should I approach this?

My code is as follows:

<select id="test">
    <option>Size 9</option>
    <option>Size 14</option>
    <option>Size 8</option>
    <option>Size 11</option>
</select>

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

I will need a solution to sort the drop down even if there are only characters, not mixed.

jsfiddle

Upvotes: 1

Views: 4059

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You could use following snippet which btw will set value for each option:

DEMO jsFiddle

$("#test").html($("#test option").val(function(){
    return this.text.match(/\d+/);
}).sort(function (a, b) {
    var a = parseInt(a.value,10), b = parseInt(b.value,10);
    return a < b ? -1 : 1;
}));

Or without setting values:

DEMO

$("#test").html($("#test option").sort(function (a, b) {
    var a = parseInt(a.text.match(/\d+/),10), b = parseInt(b.text.match(/\d+/),10);
    return a < b ? -1 : 1;
}));

EDIT: ( following comment)

You could skip sorting default option like this:

DEMO

$("#test").html($("#test option").val(function (i) {
    return i !== 0 ? this.text.match(/\d+/) : this.value;
}).sort(function (a, b) {
    var a = parseInt(a.value !== ""?a.value:-1, 10),
        b = parseInt(b.value, 10);
    return a < b ? -1 : 1;
}));

Upvotes: 4

Rajesh Dhiman
Rajesh Dhiman

Reputation: 1896

When you compare text two text field, that contains some numbers. Comparison works on first numeric value only.

For example : if we compare size 9 with size 14, then you can get surprising results like size 9 is greater than size 14. This is because only first numeric value is being compare so for 14 the value is numeric value is 1.

In your case a simple solution might be applying a value field to options and using value for comparisons.

<select id="test">
    <option value ="9">Size 9</option>
    <option value ="14">Size 14</option>
    <option value ="8">Size 8</option>
    <option value ="11">Size 11</option>
</select>

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

Upvotes: 0

Kudlas
Kudlas

Reputation: 659

You can sort by value

html

<select id="test">
    <option value='9'>Size 9</option>
    <option value='14'>Size 14</option>
    <option value='8'>Size 8</option>
    <option value='11'>Size 11</option>
</select>

js

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

DEMO

Upvotes: 0

Related Questions