Question

I have a large HTML table with onclick events on each td (with the class myClass).

Is there a way to make it so that by clicking on a TD I change the background colour for all tds with the same value, or to highlight them in any other way?

What I am looking for is a quick way to show tds with the same value without the need to filter the table.

Example TRs:

<tbody>
    <tr>
        <td class="myClass">Value 1</td>
        <td class="myClass">Value 5</td>
        <td class="myClass">Value 3</td>
        <td class="myClass">Value 1</td>
        <td class="myClass">Value 2</td>
    </tr>
    <tr>
        <td class="myClass">Value 3</td>
        <td class="myClass">Value 2</td>
        <td class="myClass">Value 1</td>
        <td class="myClass">Value 5</td>
        <td class="myClass">Value 2</td>
    </tr>
</tbody>
Was it helpful?

Solution

This will make it so that whenever you click on a td, it will highlight all the tds with the same text yellow.

$("td").click(function() {
  var value = $(this).text();
  $("td")
   .css("background-color", "")
   .filter(function(){
     return $(this).text() === value;
   })
  .css("background-color", "yellow");
});

You can see this in action on jsFiddle.

OTHER TIPS

Here is a straight up jquery answer that is brute force but I think goes along the lines of what you want

$('.myClass').on('click',function(choice){
   var choiceText = $(choice).text();
   $('.myClass').each(function(index, element){
       if($(element).text() === choiceText){
           //do whatever you need
       }

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