Search code examples
javascriptjquerybuttononclicktoggleclass

jQuery: toggleClass, multiple <td>-elements, only one highlighted


HTML

<table cellpadding=10>
  <tr>
    <td id="g1" class="tdback">test 1</td>
    <td>
      <button onclick="clickHighlightTd(g1);">click</button>
    </td>
  </tr>
  <tr>
    <td id="g2" class="tdback">test 2</td>
    <td>
      <button onclick="clickHighlightTd(g2);">click</button>
    </td>
  </tr>
  <tr>
    <td id="g3" class="tdback">test 3</td>
    <td>
      <button onclick="clickHighlightTd(g3);">click</button>
    </td>
  </tr>
  <tr>
    <td id="g4" class="tdback">test 4</td>
    <td>
      <button onclick="clickHighlightTd(g4);">click</button>
    </td>
  </tr>
</table>

CSS

.tdback {
  background-color: #ffffff;
}

.tdhighlight {
  background-color: #999999;
}

JS

function clickHighlightTd(str) {
  $(str).toggleClass('tdhighlight');
}

I want to click on a button, the td in the same line should toggle the class to ".tdhighlight" and when clicking on any other button, the previous (or all other td) should get the standard class (".tdback") and the td in this line should get highlighted.

Here is a JSFiddle. Unfortunately the code works on my site, but not in JSFiddle. Maybe I have missed something up.

Thanks for your help!


JSFiddle



Solution

  • The solution is finally here: https://jsfiddle.net/h11pqubz/8/