Question

Stuck on what seems like a simple task and have tried a few variations with no success. I have a table that has some radios in the tags. Each radio coorelates with a group of data that is in the same column . When I click on the radios in the , I want to add/remove a class or toggleClass's so that each column is highlighted as a user selects different options.

Created a sample fiddle of what I am trying to accomplish here:

JS FIDDLE

 <form id="myForm">
 <table>
<tr>
<th class="highlightMe option"> <input type="radio" name="radioName" value="1" checked="checked" class="option"/>one 
 </th>
 <th class="noClass option"><input type="radio" name="radioName" value="2" class="option"/>two 
 </th>
  <th class="noClass option"><input type="radio" name="radioName" value="3" class="option"/>three 
  </th>
  </tr>
  <tr>
   <td class="highlightMe">Highlight Me</td>
   <td class="noClass option">Or Highlight Me</td>
   <td class="noClass option">Or highlight three</td>
   </tr>
   </table>
   </form> 

A simple class with background to highlight all of the table data columns:

.highlightMe {
background:#D32F32;
}

One of the failing scripts I have tried:

  $('.option').each(function() {
var $this = $(this);
if($this.attr('checked')) {
    $this.addClass('highlightMe');
 } else {
    $this.removeClass('highlightMe');
 }
});
Was it helpful?

Solution

Try

jQuery(function($) {
    $('.option').change(function() {
        var $this = $(this), $td = $this.parent(), $tr=$td.parent();

        $tr.next().add($tr).find('.highlightMe').removeClass('highlightMe');

        if(this.checked) {
            $tr.next().find('td').eq($td.index()).add($td).addClass('highlightMe')
        }
    });
});

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top