PhilG PhilG - 6 months ago 14
jQuery Question

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





Answer

You're almost there:

function clickHighlightTd(str) {
  // remove class from all TD elements
  $("td").removeClass('tdhighlight');
  // your choice: use addClass/toggleClass as you prefer
  $(str).addClass('tdhighlight');
}

Updated fiddle: https://jsfiddle.net/h11pqubz/3/

By the way, the TDs never "lose" the class tdback - the other class tdhighlight is added additionally (that means, the TDs have both classes at the same time), and when tdhighlight is removed, they still have tdback.