Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New Coder
    Join Date
    Jun 2006
    Posts
    46
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Sort Select list in numerical order

    Hi,

    I have a few select lists that are sorted alphabetically using the below code but it isn't sorting the numbers right. Its displaying like the example below:

    Its doing:

    150
    200
    50

    When it should be:

    50
    150
    200

    Id like to sort just this one select list in numerical order. Can anyone help please as I am stuck and just learning Javascript

    Code:
    function sortDropDownListByText() {
        // Loop for each select element on the page.
        $("select").each(function() {
             
            // Keep track of the selected option.
            var selectedValue = $(this).val();
     
            // Sort all the options by text. I could easily sort these by val.
            $(this).html($("option", $(this)).sort(function(a, b) {
                return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
            }));
     
            // Select one option.
            $(this).val(selectedValue);
        });
    }
    Many thanks
    Joe

  • #2
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts
    Have you tried...
    Code:
                return a.text == b.text ? 0 : Number(a.text) < Number(b.text) ? -1 : 1

  • #3
    New Coder
    Join Date
    Jun 2006
    Posts
    46
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Hi!

    Thanks alot for the reply

    I have just tried what you said and it still displays them as:

    150
    200
    50

    I assume it goes here (I'm new to Javascript lol)

    Code:
    function sortDropDownListByText() {
        // Loop for each select element on the page.
        $("select").each(function() {
             
            // Keep track of the selected option.
            var selectedValue = $(this).val();
     
            // Sort all the options by text. I could easily sort these by val.
            $(this).html($("option", $(this)).sort(function(a, b) {
                return a.text == b.text ? 0 : Number(a.text) < Number(b.text) ? -1 : 1
            }));
     
            // Select one option.
            $(this).val(selectedValue);
        });
    }
    Many thanks
    Joe

  • #4
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,467
    Thanks
    3
    Thanked 495 Times in 482 Posts
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <select>
     <option >150</option>
     <option >100</option>
     <option >10</option>
    </select>
    <select>
     <option >150</option>
     <option >15</option>
     <option >5</option>
     <option >10</option>
    </select>
    
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function Sort(){
     var ss=document.getElementsByTagName('Select'),s,opts,ary,z0=0,z1=0,z2=0;
     for (;z0<ss.length;z0++){
      s=ss[z0];
      opts=s.options;
      ary=[];
      for (z1=0;z1<opts.length;z1++){
       ary.push([opts[z1],opts[z1].text]);
      }
      ary=ary.sort(function(a,b){ return a[1]-b[1]; });
      for (z2=0;z2<ary.length;z2++){
       s.appendChild(ary[z2][0]);
      }
      s.selectedIndex=0;
     }
    }
    
    Sort();
    /*]]>*/
    </script>
    </body>
    
    </html>
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by Gibson View Post
    Code:
    function sortDropDownListByText() {
        // Loop for each select element on the page.
        $("select").each(function() {
    
             var that=$(this);
    
            // Keep track of the selected option.
            var selectedValue = $(this).val();
     
            // Sort all the options by text. I could easily sort these by val.
            $(this).html($("option", $(this)).toArray().sort(function(a, b) {
                return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
            })).map(  that.append.bind(that)  );
     
            // Select one option.
            $(this).val(selectedValue);
        });
    }

    you were actually very close (changes in red):
    Code:
    function sortDropDownListByText() {
        // Loop for each select element on the page.
        $("select").each(function() {
    
             var that=$(this);
    
            // Keep track of the selected option.
            var selectedValue = $(this).val();
     
            // Sort all the options by text. I could easily sort these by val.
            $(this).html($("option", $(this)).toArray().sort(function(a, b) {
                return a.text == b.text ? 0 : +a.text < +b.text ? -1 : 1
            })).map(  function(a){  that.append(a); });
     
            // Select one option.
            that.val(selectedValue);
        });
    }
    Last edited by rnd me; 10-31-2013 at 06:31 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #6
    Regular Coder
    Join Date
    Mar 2006
    Posts
    725
    Thanks
    35
    Thanked 132 Times in 123 Posts
    This method will sort numbers numerically,
    alphabetic characters by their lower case,
    and mixed numbers and strings naturally- 'abc21' precedes 'abc100'.

    For nested arrays, the sort will compare the elements at the index passed as its argument.

    Code:
    Array.prototype.naturalSort= function(index/*optional*/){
    	var T= this.sort(), L= T.length, i, who, next, 
    	isi= typeof index== 'number', 
    	rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
    	function nSort(aa, bb){
    		var a= aa[0], b= bb[0], a1, b1, i= 0, n, L= a.length;
    		while(i<L){
    			if(!b[i]) return 1;
    			a1= a[i];
    			b1= b[i++];
    			if(a1!== b1){
    				n= a1-b1;
    				if(!isNaN(n)) return n;
    				return a1>b1? 1:-1;
    			}
    		}
    		return b[i]? -1:0;
    	}
    	for(i= 0; i<L; i++){
    		who= T[i];
    		next= isi? T[i][index] || '':who;
    		T[i]= [String(next).toLowerCase().match(rx), who];
    	}
    	T.sort(nSort);
    	for(i= 0; i<L; i++){
    		T[i]= T[i][1];
    	}
    	return this;
    }
    Last edited by mrhoo; 11-01-2013 at 02:12 AM. Reason: spelling


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •