1

I have a very simple jsFiddle that use jQuery caching and delegate. How can I make handler dynamic enough that when user clicks the first group checkbox, it highlights only the rows below it and when user selects the second group checkbox, it should select the rows below the second checkbox.

I can have n groups and n rows under the group checkbox. For performance, I am trying to cache everything and then in handler I want to be able to select the desired group rows based on checkbox using designated classes to identify group. Also, I want to identify when user clicks on data cell.

I tried different options to identify the object, by I guess obj.type doesn't return what I thought would give me the type. Any help would be much appreciated.

Code:

var elements = $(".data");

$("table").delegate("td", "click", function(evt){
    var obj = $(this);

    switch (obj.type) {
        case: "checkbox":
            //select all elements under this group
            elements.addClass('blue');
            break;
        case: "td":
            //I know this is not the right case, not sure how to trap a cell click
            //apply class 'red'
            break;
        default:
            elements.addClass('green');
            break;
    }    
});

Supporting HTML and CSS

<table>
  <tbody>
    <tr>
        <td>
            <input type="checkbox" id="chkFirst" />
        </td>
    </tr>
    <tr class="data">
        <td class="first">
            A
        </td>
    </tr>
    <tr class="data">
        <td class="first">
            B
        </td>
    </tr>
    <tr class="data">
        <td class="first">
            C
        </td>
    </tr>
     <tr class="data">
        <td>
            <input type="checkbox" id="chkSecond" />
        </td>
    </tr>
    <tr class="data">
        <td class="second">
            Aa
        </td>
    </tr>
        <tr class="data">
        <td class="second">
            Bb
        </td>
    </tr>
  </tbody>
</table>

.blue {
    color: blue;
}
.red {
    color: red;
}
.green {
    color: green;
}
Sri Reddy
  • 6,832
  • 20
  • 70
  • 112

1 Answers1

0

Have you tried evt.target? That should be the HTML element that triggered the click.

Try this sample jsFiddle for an illustration. Since you know which cell it is, you can go up the DOM heirarchy to figure out, which row or table got clicked.

Umar Farooq Khawaja
  • 3,925
  • 1
  • 31
  • 52