Search code examples
sortingdomnodelist

How to sort and search dom table elements created using ajax


I tried this to search dom elements and display matching rows,but it doesnt work in some columns like duration and bytes.It works for elements which repeat for example if there are 507 value twice in bytes it works but dont work for 411. I am reading file contents and tabulating it, then need to sort rows when header is clicked and apply a filter.

<!DOCTYPE html>
<html>
 <meta charset="UTF-8"> 
    <head>
        <style type="text/css">
             body
             {
                 font-family: Arial;
                    font-size: 10pt;
             }
            table
            {
                 border: 1px solid #ccc;
                  margin: auto;
              empty-cells: hide;
            }
             table th
             {
                 background-color: GREY;
                    color: #333;
                    font-weight: bold;
            cursor:pointer;
                }
            table th, table td
             {
                 padding: 5px;
                 border: 1px solid #ccc;
                 border-color: #ccc;

               }

             #sear
        {
         background-color: black;

        height:30px;
        width:105%;
        align : center;
        }
        tr:nth-child(even) {
         background-color: #f2f2f2
        }

            tr:hover {
         background-color: silver;
        }
          </style>

     <meta name="viewport" content="width=device-width,height=device-height, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>

        <div id="sear" align = center>
        <input type="text" id="filter" placeholder="Search" title="Type a name" >
        </div>
        <div id="demo" align = center >

        </div>

        <script>
            window.onload = function() {
             var demo = document.getElementById("demo");
              if(window.XMLHttpRequest){
                 var xhttp = new XMLHttpRequest();
              }
              else{
                   var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
               }
               xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200 || this.status == 0) {
              var responseText= xhttp.responseText;
  //alert(responseText);
            //  console.log(this.responseText);
              document.getElementById("filter").onkeyup = filterRows;
              var ROW_DELIMITER = "\n",  CELL_DELIMITER = " ";

              var tableObj = { headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", 

"Hierarchy code", "Type"], 
                rows: []
               };
            }

             function convert(responseText) {
               tableObj.rows = convertToArray(responseText);
               buildTable(tableObj.headers, tableObj.rows);
              };

            function convertToArray(text) {
                 return text.split(ROW_DELIMITER).map(function(row) {
                     return row.split(CELL_DELIMITER);
                    });
            }


              function filterRows() {
                    var input = this;
                    var rows = tableObj.rows.filter(function(row) {

                      var matches = row.filter(function(cell) { 
                            return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
                        });

                     return matches.length > 0;
                              });

                      buildTable(tableObj.headers, rows);
            }



              function sortRows() {

                   var index = this.dataset.index;
                   tableObj.rows.sort(function(rowA, rowB) {
                      var textA = rowA[index].toUpperCase(), textB = rowB[index].toUpperCase();
                     if (textA < textB) {
                       return -1;
                      }
                    if (textA > textB) {
                       return 1;
                    }
                       return 0;
                    });

                 buildTable(tableObj.headers, tableObj.rows);
            }


            function buildTable(headers, rows) {
                  var table = document.createElement('table');
                      var tr = document.createElement('tr');
                   table.appendChild(tr);

                 for (var i = 0; i < headers.length; i++) {
                         th = document.createElement('th');
                         tr.appendChild(th);
                         th.innerHTML = headers[i];
                         th.onclick = sortRows; 
                          th.dataset.index = i;
                    }

                 for (var j = 0; j < rows.length-1; j++) {
                          tr = document.createElement('tr');
                       table.appendChild(tr);
                       tr.dataset.index = j;
                         for (var k = 0; k < rows[j].length ; k++) {
                              var td = document.createElement('td');

    /*                    if(k==0)
                          {
                            var d = new Date( rows[j][k]* 1000),    
                            yyyy = d.getFullYear(),
                            mm = ('0' + (d.getMonth() + 1)).slice(-2),  
                            dd = ('0' + d.getDate()).slice(-2),         
                            hh = d.getHours(),
                            h = hh,
                            min = ('0' + d.getMinutes()).slice(-2),     
                            ampm = 'AM',
                            time;

                            if (hh > 12) {
                                h = hh - 12;
                                ampm = 'PM';
                            } else if (hh === 12) { 
                                h = 12;
                                ampm = 'PM';
                            } else if (hh == 0) {
                                h = 12;
                            }


                            rows[j][k] = dd + '.' + mm + '.' + yyyy + ', ' + h + ':' + min + ' ' + ampm;


                        }
    */

                        tr.appendChild(td);
                             td.innerHTML = rows[j][k];
                            td.dataset.index = k;
                    }
                }
                demo.innerHTML = '';
                demo.appendChild(table);
          }

         convert(responseText);
        };
     xhttp.open("GET", "sample.txt", true);
     xhttp.send(null);
    };
    </script>
</body>
</html>

Solution

  • Here is the updated code:

    window.onload = function() {
                var demo = document.getElementById("demo");
                if (window.XMLHttpRequest) {
                    var xhttp = new XMLHttpRequest();
                } else {
                    var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200 || this.status == 0) {
                        var responseText = xhttp.responseText;
                        console.log(this.responseText);
                        document.getElementById("filter").onkeyup = filterRows;
                        var ROW_DELIMITER = "\n",
                            CELL_DELIMITER = " ";
                        var tableObj = {
                            headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", "Hierarchy code", "Type"],
                            rows: []
                        };
                    }
    
                    function convert(responseText) {
                        if(responseText!='' && typeof responseText != 'undefined'){
                            tableObj.rows = convertToArray(responseText);
                            buildTable(tableObj.headers, tableObj.rows);
                        }
                    };
    
                    function convertToArray(text) {
                        return text.split(ROW_DELIMITER).map(function(row) {
                            return row.split(CELL_DELIMITER);
                        });
                    }
    
    
                    function filterRows() {
                        var input = this;
                        var rows = tableObj.rows.filter(function(row) {
                            var matches = row.filter(function(cell) {
                                //console.log(cell.toUpperCase())
                             //   console.log(input.value.toUpperCase())
                             //   console.log(cell.toUpperCase().indexOf(input.value.toUpperCase()))
                                return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
                            });
                            return matches.length > 0;
                        });
                        buildTable(tableObj.headers, rows);
                    }
    
    
    
                    function sortRows() {
    
                        var index = this.dataset.index;
                        tableObj.rows.sort(function(rowA, rowB) {
                            var textA = rowA[index].toUpperCase(),
                                textB = rowB[index].toUpperCase();
                            if (textA < textB) {
                                return -1;
                            }
                            if (textA > textB) {
                                return 1;
                            }
                            return 0;
                        });
    
                        buildTable(tableObj.headers, tableObj.rows);
                    }
    
    
                    function buildTable(headers, rows) {
                        var table = document.createElement('table');
                        var tr = document.createElement('tr');
                        table.appendChild(tr);
    
                        for (var i = 0; i < headers.length; i++) {
                            th = document.createElement('th');
                            tr.appendChild(th);
                            th.innerHTML = headers[i];
                            th.onclick = sortRows;
                            th.dataset.index = i;
                        }
    
                        for (var j = 0; j <= rows.length - 1; j++) {
                            tr = document.createElement('tr');
                            table.appendChild(tr);
                            tr.dataset.index = j;
                            for (var k = 0; k < rows[j].length; k++) {
                                var td = document.createElement('td');
    
    
                                tr.appendChild(td);
                                td.innerHTML = rows[j][k];
                                td.dataset.index = k;
                            }
                        }
                        demo.innerHTML = '';
                        demo.appendChild(table);
                    }
                    convert(responseText);
                };
                xhttp.open("GET", "sample.txt", true);
                xhttp.send(null);
            };