2

hi i am new to web page developer, i need to sort my table in date wise and alphabet wise on click of table header

enter image description here

this is my table.... the data's inside the table are generated dynamically using ajax....

my need is

  • on click of date header it should sort according to date
  • on click of notify header it should sort according to alphabet

please give some ideas or suggestions about this .......

1
  • numerous jQuery plugins for tables, easy to find in web search Commented Mar 25, 2013 at 6:39

5 Answers 5

4

I made example using jQuery library, and added it in http://jsfiddle.net/bURg4/2/

jQuery selector returns is array object, which has native array sort function .

$('table tbody tr').sort( function( a , b ) {

     // do compare here
});

Hope this will helps ..

copy and paste following code into a file .. rename it into test.html

<html>
    <head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    </head>
    <body>
        <table border="1">
            <thead>
                <tr>
                    <th data-key="id" data-column="0" data-order="asc">id</th>
                    <th data-key="date" data-column="1" data-order="asc">date</th>
                    <th data-key="notify" data-column="2" data-order="asc">notify</th>

                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>31-03-2013 06:12:57 PM</td>
                    <td>gold</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>31-03-2013 06:14:57 PM</td>
                    <td>diamond</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>31-03-2013 06:10:57 PM</td>
                    <td>silver</td>
                </tr>
            </tbody>
        </table>    
        <script type="text/javascript">

            function getDate( str ) {

                var ar =  /(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2}) ([AM|PM]+)/ 
                     .exec( str ) 

                return new Date(
                    (+ar[3]),
                    (+ar[2])-1, // Careful, month starts at 0!
                    (+ar[1]),
                    (+ar[4])+ ( ar[7]=='PM'? 12 :0 ),
                    (+ar[5]),
                    (+ar[6])
                );
            };

            $( function(){


                var sorter = {

                    order   : [1,-1],
                    column  : 0 ,
                    key     :'id' ,

                    setOrder : function( k ){

                        this.order  = ({ 
                            asc :[1,-1], desc:[-1,1] 
                        })[k] || this.order ;

                        return this;
                    },
                    setColumn : function( c ){

                        this.column  = c || this.column ;
                        return this;
                    },

                    setKey : function( k ) {
                        this.key  = k || this.key;
                        return this;
                    },

                    sort : function( els ) {

                        var sortFunc = this.key;

                        return els.sort( this[ sortFunc ]);        
                    },

                    getValue : function( a, b ){

                        return {
                            a : $(a).find('td:eq('+ sorter.column +')').text(),
                            b : $(b).find('td:eq('+ sorter.column+')').text()
                        }
                    },
                    comp : function( val ) {

                            if ( val.a == val.b ) {
                                return 0;
                            }

                            return  val.a > val.b ? 
                                    sorter.order[0]:sorter.order[1] ; 

                    },
                    id : function( a , b ){

                            var val = sorter.getValue(a,b);

                            val.a = parseInt( val.a , 10 );
                            val.b = parseInt( val.b , 10 );

                            return sorter.comp( val );        

                    },

                    notify : function( a , b ){

                            var val = sorter.getValue(a,b);
                            return sorter.comp( val );           

                    },
                    date : function( a , b ){

                            var val = sorter.getValue(a,b);

                            val.a = getDate( val.a );
                            val.b = getDate( val.b );

                            return sorter.comp( val ); 

                    }
                }

                $('table thead').on('click', 'th', function(){

                        var sorted = sorter.setOrder( $(this).attr('data-order') )
                                           .setColumn( $(this).attr('data-column') )
                                           .setKey( $(this).attr('data-key') )
                                           .sort(  $('table tbody tr') );


                        $('table tbody').empty().append( sorted );  

                        $('table thead th').not( this )
                                           .attr('data-order' ,'asc');

                        $(this).attr(
                            'data-order',  
                            ( $(this).attr('data-order') == 'asc' ? 'desc' :'asc') 
                        );

                });
            });
        </script>

    </body>
</html>   
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the help but can u help me without on load function
@Kumar which load function ? did u check jsfiddle ?
i tried your code it shows error(TypeError: Cannot read property '3' of null) when i clicked the date column in my code....
i have made some change in question just see it when i applied the code it shows error(TypeError: Cannot read property '3' of null) in date column please help....
again the same error coming can u give fiddle for the changed table
2

I would use a small jquery plugin.

I have tried http://www.datatables.net/ but think its too large for my need thats a little bigger than yours so I would suggest http://tablesorter.com/docs/ which fits you speification perfect.

You'll find demos on their sites.

Comments

2

Store the corresponding values in an array and do sorting

To sort array by date, Use this

array.sort(function(a,b){
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});

To sort array by alphabet , use basic sort() function

Live Demo for sorting the date and time

1 Comment

See my edited post .. I have attached a link for sorting the date and time
1
function sortAsc(a, b) {
    var aSort = a.Text.toLowerCase(), //Text is the field on which we make sort
        bSort = b.Text.toLowerCase();
    if (aSort === bSort) return 0;
    return aSort < bSort ? 1 : -1;
}
function sortDesc(a, b) {
    var aSort = a.Text.toLowerCase(), //Text is the field on which we make sort
        bSort = b.Text.toLowerCase();
    if (aSort === bSort) return 0;
    return aSort > bSort ? 1 : -1;
}

i use these two methods for sorting Json Obejct

call them as [jsonObject].sort(sortDesc) or [jsonObject].sort(sortAsc)

1 Comment

This will not sort dates correctly unless they are supplied as yyyy-mm-dd.
0

You may give id for date column in increasing manner that is Row 1 col1 will be date_1 then row2 and col1 will be date_2 like that, apply it to both columns (notify_1,notify_2,...). Have a hidden field on form that consists the no of rows. on the basis of it you may apply a loop up to it then can use any sorting algo on td's inner html.

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.