javascript – Sort a table alphabetically using JS or some basic language-ThrowExceptions

Exception or error:

I am trying to improve a table that I’m working on for quite some time now. May I just ask quickly if it’s possible to add a feature where a user can sort this table alphabetically?

NOTE: And please keep the words a bit simple (because I’m not a programmer at all but I will try my best to understand any tips)

First, here’s what it looks like :

enter image description here
And finally, here is the combination of code:

document.addEventListener("DOMContentLoaded", function() {
  var $input = document.getElementById("myInput"),
      $table = document.getElementById("myTable"),
      $$tr   = $table.querySelectorAll("tbody tr"),
      $noResults = $table.querySelector("tfoot tr");

  // Add the normalized name+country as a property to each tr, so that you don't have
  // to compute that every time when performing a search
  for (var i = 0; i < $$tr.length; i++) {
    var $$td    = $$tr[i].querySelectorAll("td"),
          name    = $$td[0].innerText,
        country = $$td[1].innerText;
    $$tr[i].normalizedValue = normalizeStr( name + " " + country );
  }
  // When typing or pasting text, perform a search
  $input.addEventListener("input", performSearch);

  function performSearch() {
    var filter = normalizeStr(this.value),
            resultCount = 0;
    for (var i = 0; i < $$tr.length; i++) {
      // If the filter is not empty and matches that row
      var isMatch = filter.length > 0 && $$tr[i].normalizedValue.includes(filter);
      if (isMatch) { resultCount++; }
      // Toggle a 'visible' class
      $$tr[i].classList[isMatch ? "add" : "remove"]("visible");
    }
    // Show the "no results" message if there are no results
    // and the search query is not empty
    var showNoResultsMessage = resultCount === 0 && filter.length > 0;
    $noResults.classList[showNoResultsMessage ? "add" : "remove"]("visible");
  }

  // Creating a reusable function will allow us to make
  // changes to it only in one place 👍
  function normalizeStr(str) {
    // In case str is falsey, use an empty string
    return (str || '').toUpperCase().trim();
  }
});
*{box-sizing:border-box
}
#myInput{
background-image:url(/css/searchicon.png);
background-position:10px 10px;
background-repeat:no-repeat;
width:100%;
font-size:16px;
padding:12px 20px 12px 40px;
border:1px solid #ddd;
margin-bottom:12px
}
#myTable{
border-collapse:collapse;
width:100%;
border:1px solid #ddd;
font-size:18px
}
#myTable td,
#myTable th{
text-align:left;
padding:12px
}
#myTable tr{
border-bottom:1px solid #ddd
}
#myTable thead tr, /* notice the use of thead */
#myTable tr:hover {
  background-color: #f1f1f1;
}

#myTable tbody tr {
  display: none; /* Hide rows by default */
}

#myTable tbody tr.visible {
  display: table-row; /* Show them when they match */
}

#myTable tfoot tr:not(.visible) {
  display: none; /* Hide the "no results" message if not .visible */
}

#myTable tfoot td {
  text-align: center;
}
<!-- Try not using `on...=""` attributes. Separating HTML and JS is better practice -->
<input type="text" id="myInput" placeholder="Search for an author or a title" title="Type in a name" />

<table id="myTable">
  <!-- Use <thead> and <tbody> to separate data from headers -->
  <thead>
    <tr>
      <th style="width:60%;">Title</th>
      <th style="width:40%;">Author</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Treasure Island</td>
    <td>Robert Louis Stevenson</td></tr>

    <tr><td>The Complete Sherlock Holmes</td>
    <td>Arthur Conan Doyle</td></tr>

    <tr><td>The Lord of the Rings</td> 
    <td>J.R.R. Tolkien</td> </tr>

    <tr><td>The Interpretation of Dreams</td> 
    <td>Sigmund Freud</td></tr>

    <tr><td>Tales of Horror</td> 
    <td>H.P. Lovecraft</td></tr>

    <tr><td>The Trial</td> 
    <td>Franz Kafka</td></tr>

    <tr><td>The Prince</td> 
    <td>Niccolo Machavielli</td></tr>

    <tr><td>Old Possum's Book of Practical Cats</td> 
    <td>T.S. Eliot</td></tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="2">No results found.</td>
    </tr>
  </tfoot>
</table>

I would really appreciate your help guys. Thanks a lot!

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *