kannan D.S
kannan D.S

Reputation: 1101

Table data click event issue

How to alert table data where corresponding table head id="0". I have a dynamic table here with many table heads. one table head id is 0. how can i make an alert when clicked on table data corresponding table head.

<table>
<tr>
<th>heading1</th>
<th id="0">heading2</th>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
<tr>
<th>heading11</th>
<th id="1">heading12</th>
<td>data1</td>
<td>data2</td>
<td>data3</td>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
</table>

$("th#0 td").live('click',function(){
alert("clicked");
});

Upvotes: 0

Views: 66

Answers (3)

T J
T J

Reputation: 43156

Looks like most of the other answers assumes that <th> and <td> containing data are siblings (Well it is, in the given HTML)

The proper table structure should be like

<table>
  <thead>
    <tr>
        <th>heading1</th>
        <th id="0">heading2</th>
        <th>heading11</th>
        <th id="1">heading12</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>data1</td>
        <td>data2</td>
        <td>data3</td>
        <td>data4</td>
        <td>data5</td>
        <td>data6</td>
    </tr>
    <tr>
        <td>data1</td>
        <td>data2</td>
        <td>data3</td>
        <td>data4</td>
        <td>data5</td>
        <td>data6</td>
    </tr>
  </tbody>
</table>

You can do this:

var index= $("#0").index();
$("table").on("click", "tr td:nth-child("+(++index)+")", function () {
    alert("click");
})

Demo

Upvotes: 0

Sam1604
Sam1604

Reputation: 1489

Use the following query I hope it solves your query,

var dataa=$("th#0").siblings('td');
dataa.on('click', function(){
alert("clicked");
});

Here is a DEMO

Upvotes: 0

selvakumar gopal
selvakumar gopal

Reputation: 85

$("#0~td").on('click',function(){
alert("clicked");

});

Upvotes: 1

Related Questions