1

I'm trying to sort the options by value in selectbox. Sorting is fine by using the below code.But i have option value null, it goes to bottom which should be at top.

$(this).html($("option", $(this)).sort(function(a, b) { 
    var arel = parseInt($(a).attr('value'), 10);
    var brel = parseInt($(b).attr('value'), 10);
    return arel == brel ? 0 : arel < brel ? -1 : 1 
}));

Source: Sorting Select box with jQuery

Actual Result:

<select name="option[285]">
<option value="298">Blazing Yellow</option>
<option value="299">Jet Black</option>
<option value="300">Tabacco Brown</option>
<option value="301">Optical White</option>
<option value="302">Fiery Red </option>
<option value="" selected="selected"> --- Please Select --- </option>
</select>

Expected Result:

<select name="option[285]">
<option value="" selected="selected"> --- Please Select --- </option>
<option value="298">Blazing Yellow</option>
<option value="299">Jet Black</option>
<option value="300">Tabacco Brown</option>
<option value="301">Optical White</option>
<option value="302">Fiery Red </option>
</select>

1 Answer 1

3

The problem seems to be that parseInt('') given NaN which when compared using arel < brel gives wrong result

$(this).html($("option", $(this)).sort(function(a, b) { 
    var arel = parseInt($(a).attr('value'), 10) || 0;
    var brel = parseInt($(b).attr('value'), 10)|| 0;
    return arel == brel ? 0 : arel < brel ? -1 : 1 
}));

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.