Table click toggle

by Wil Chow

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="vehicles">
  <tr>
    <th>Type</th>
    <th>Color</th>
    <th>Wheels</th>
  </tr>
  <tr>
    <td>Car</td>
    <td>Red</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Blue</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Car</td>
    <td>Blue</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Red</td>
    <td>2</td>
  </tr>
</table>

JavaScript

$(function () {
		var last_type = null;
    var filtered = false;
    $( "td" ).on( "click", function() {
    		console.log("last_type: "+last_type);
        var type = $(this).text();
        console.log("type: "+type);
        if(filtered && last_type == type) {
        	// type is already filtered. Show all.
        	$("tr, td").show();
          last_type = null; // reset
          filtered = false; // reset
        } else {
        	$("tr, td").show(); // show all before filtering
        	$('td:first-child').parent('tr:not(:contains('+type+'))').hide();
          filtered = true; // set filter flag to true
        }
        last_type = type; // set last type clicked
    });
});