Live-Search on a table

This fiddle demonstrates how one may execute a dynamic search on a table's unique identifier column. This fiddle is a response to stackoverflow issue: http://stackoverflow.com/questions/12433304/live-search-through-table-rows

by Behzad Khosravifar

HTML

<table>
   <tr>
      <th>Unique ID</th>
      <th>Random ID</th>
   </tr>
   <tr>
      <td>214215</td>
      <td>442</td>
   </tr>
   <tr>
      <td>1252512</td>
      <td>556</td>
   </tr>
   <tr>
      <td>2114</td>
      <td>4666</td>
   </tr>
   <tr>
      <td>3245466</td>
      <td>334</td>
   </tr>
   <tr>
      <td>24111</td>
      <td>54364</td>
   </tr>
</table>
<br />
<input type="text" id="search" placeholder="  live search"></input>

CSS

table,
tr,
td,
th {
   border: 1px solid blue;
   padding: 2px;
}

table th {
   background-color: #999999;
}

em {
   background-color: yellow
}

JavaScript

function removeHighlighting(highlightedElements) {
   highlightedElements.each(function() {
      var element = $(this);
      element.replaceWith(element.html());
   })
}

function addHighlighting(element, textToHighlight) {
   var text = element.text();
   var highlightedText = '<em>' + textToHighlight + '</em>';
   var newText = text.replace(textToHighlight, highlightedText);

   element.html(newText);
}

$("#search").keyup(function() {
   var value = this.value.toLowerCase().trim();

   removeHighlighting($("table tr em"));

   $("table tr").each(function(index) {
      if (!index) return;
      $(this).find("td").each(function() {
         var id = $(this).text().toLowerCase().trim();
         var matchedIndex = id.indexOf(value);
         if (matchedIndex === 0) {
            addHighlighting($(this), value);
         }
         var not_found = (matchedIndex == -1);
         $(this).closest('tr').toggle(!not_found);
         return not_found;
      });
   });
});