1

I fund a very nice sorting function here How may I sort a list alphabetically using jQuery? works almost perfect except that it looks like sorts by first charachter only , for example if you have something like

0-5000
5001-10000
10001-15000
15001-20000

the order will look like

0-5000
10001-15000
15001-20000
5001-10000

instead

0-5000
5001-10000
10001-15000
15001-20000

I redid the function for every select in the form

var mylist = $('#myformid select');

$(mylist).each(function (sorter, elm) { 
  var listitems = $(this).children('option.myoptionclass').get();
   listitems.sort(function(a, b) {
      var compA = $(a).text().toUpperCase();
      var compB = $(b).text().toUpperCase();
      return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
   })
     $.each(listitems, function(idx, itm) { 
          $(this).parent().append(itm); 
      });

});

here is live example

http://jsfiddle.net/sQsZQ/6/

any help is welcome!

Community
  • 1
  • 1
Benn
  • 4,840
  • 8
  • 65
  • 106

2 Answers2

3

I editted your fiddle: http://jsfiddle.net/CBD33/2/ I'm using parseInt so the comparison looks like this now:

listitems.sort(function(a, b) {
  var compA = $(a).text().toUpperCase();
  var compB = $(b).text().toUpperCase();
  compA = (parseInt(compA,10) || compA)
  compB = (parseInt(compB,10) || compB)              


  return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})

If the first character of the string value given to parseInt is a numeral, it will parse everything up to the first non-digit character. If the first character isn't a numeral, it'll return NaN. My use of || there is rather lazy, but I'm sure you can come up with a better condition.

KGZM
  • 414
  • 3
  • 5
1

You need to convert the string to numbers before you sort like this

   var compA = parseInt($(a).text().split('-')[0]);
   var compB = parseInt($(b).text().split('-')[0]);

see http://jsfiddle.net/sQsZQ/8/

Daveo
  • 19,018
  • 10
  • 48
  • 71
  • Your solution seems to work because the input was already sorted, but `'somestring'.split[0]` returns undefined. – KGZM Jul 16 '12 at 02:17
  • @Daveo thnx for submitting but did you notice that the second select is not sorting anymore because it does not have - – Benn Jul 16 '12 at 02:44
  • @Benn No I never even noticed the 2nd select box. In that case you shoud use KGZM answer – Daveo Jul 16 '12 at 02:48