Selecting table cells on click

I got this table. What I would like to do is when I click on a cell it should be highlighted, and with a second click the highlight should be cleared. and the second problem is that I would like to select multiple cells one by one while keeping the previous highlights. Fiddle here: http://jsfiddle.net/2Lu3ss9g/

<table class="color_changing" border="1" cellpadding="15">
<tbody>
  <tr>
    <td>23</td>
    <td>57</td>
    <td>62</td>
    <td>1162</td>
  </tr>
  <tr>
    <td>112</td>
    <td>5</td>
    <td>162</td>
    <td>88</td>
  </tr>
  <tr>
    <td>77</td>
    <td>62</td>
    <td>199</td>
    <td>211</td>
  </tr>
     <tr>
    <td>57</td>
    <td>64</td>
     <td>144</td>
     <td>9</td>
  </tr>

</tbody>

      

$( function() {
$('td').click( function() {
$(this).parents('table').find('td').each( function( index, element ) {
    $(element).removeClass('on');
} );
$(this).addClass('on');
} );
} );

      

+3


source to share


1 answer


Here's a simple solution using toggleClass

:

$(function () {
    $('td').click(function () {
        $(this).toggleClass('highlight');
    });
});

      



Fiddle: http://jsfiddle.net/rqeec7r4/

+4


source







All Articles