• Breaking News

    Thursday 24 September 2015

    Sort Table In JavaScript Based On Column Value

    Here We Know about how sort table using java script based on particular column value.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
       <head>
          <title> Table Sorting Example </title>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
          <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
          <script>  
             function sortTable(){
               //get table by id
               var tbl = document.getElementById("tabketpBeSorted").tBodies[0];
               var data = [];
               for(var i=0, len=tbl.rows.length; i<len; i++){
                var row = tbl.rows[i];
                var sortnr = parseFloat(row.cells[0].textContent || row.cells[0].innerText);
                if(!isNaN(sortnr)) data.push([sortnr, row]);     
               }  
               data.sort(function(x,y){
                return x[0] - y[0];
               });
               for(var i=0, len=data.length; i<len; i++){
                tbl.appendChild(data[i][1]);
               }
               data = null;
             }
             
          </script>
       </head>
       <body>
          <table class="table" id="tabketpBeSorted">
             <thead>
                <tr>
                   <th>S.No</th>
                   <th>Name</th>
                </tr>
             </thead>
             <tbody>
                <tr class="success">
                   <td>3</td>
                   <td>A</td>
                </tr>
                <tr class="danger">
                   <td>1</td>
                   <td>B</td>
                </tr>
                <tr class="info">
                   <td>2</td>
                   <td>C</td>
                </tr>
             </tbody>
          </table>
          <script>
             sortTable();
          </script>
       </body>
    </html>
    
    
    
    
    
    After Running above file we get following output



    No comments:

    Post a Comment