Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting table cells when clicked

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

$(function() {
  $('td').click(function() {
    $(this).parents('table').find('td').each(function(index, element) {
      $(element).removeClass('on');
    });
    $(this).addClass('on');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<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>
</table>
like image 629
Max Avatar asked Feb 11 '26 14:02

Max


1 Answers

Here's a simple solution using toggleClass:

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

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

like image 151
Bitwise Creative Avatar answered Feb 14 '26 03:02

Bitwise Creative