dark_knight
dark_knight

Reputation: 13

Finding the td associated to its table onclick event

I have a table like below

<table onclick="dosomething()">
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
</table>

After I click on the table, I need to find the td on which the click happened. I cannot have onclick event written on tr or td.

Upvotes: 0

Views: 113

Answers (4)

bingjie2680
bingjie2680

Reputation: 7773

Add an Id to the table and remove onClick handler. this is to seperate the behavior and content.

<table id="tableId">

since event will bubble up, capture it on table element and find the target, so you don't need to add event listener to every td.

$('#tableId').click(function(e){
     //the td is the target where event happens
     var td=e.target;
});

Upvotes: 1

Dominic Green
Dominic Green

Reputation: 10260

I would dump the onclick and do this

$("#myTable td").click(function() {
   $(this).html();    // get the value
   $(this).hide();    // hide it
   $(this).remove();  // remove it
});

<table id="myTable">
   <tr><td>11</td><td>12</td><td>13</td></tr>
   <tr><td>11</td><td>12</td><td>13</td></tr>
   <tr><td>11</td><td>12</td><td>13</td></tr>
</table>

Upvotes: 0

epignosisx
epignosisx

Reputation: 6192

$(function(){
    $("#tbl").bind("click", function(e){
        if(e.target.tagName == "TD"){
            //do your magic
        }
    });
});

Upvotes: 0

jabclab
jabclab

Reputation: 15042

You can do something like this (give your table a class of myClass- or whatever you want):

function tableClicked(td) {
    // Do something dependent on the td which was clicked
}

$(document).ready(function () {
    $("table.myClass td").click(function () {
        tableClicked(this);
    });
});

This means that you don't have to add onclick attributes to the <td> tags.

Upvotes: 1

Related Questions