Reputation: 1600
I am trying to select all the <tr>
elements inside a tbody and attach a click event by jquery but I just can not select the right elements.
This is my code:
<div id="wrapper" cellpadding="0" cellspacing="0" border="0">
<table>
<tbody>
<tr id="row_2">
<tr id="row_3">
<tr id="row_4">
...
and I tried to selct all the tr's like that:
$('#wrapper tr').mousedown(function(event) {
and
$('#wrapper > tr').mousedown(function(event) {
but it doesn't bind the click event at all.
Upvotes: 2
Views: 19211
Reputation: 75
You can do an each but you must specify the table or element
$('#clk').on('click', function(){
let trs="";
$("#wrapper #table2 tbody tr").each(function(i){
trs+=this.innerHTML;
});
alert(trs)
})
table, th, td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper" cellpadding="0" cellspacing="0" border="0">
<table id="table1">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
<table id="table2">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>March</td>
<td>$800</td>
</tr>
<tr>
<td>May</td>
<td>$180</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
</div>
<button type="button" id="clk">Clickme</button>
Upvotes: 0
Reputation: 481
It looks like invalid HTML. Use proper markup like this:
<div id="wrapper">
<table>
<tbody>
<tr>
<td>...</td>
</tr>
</tbody>
</table>
</div>
And now bind the click event.
$('#wrapper tr').mousedown(function(event) {
//do something...
});
Upvotes: 2
Reputation: 269
Try this:
$('#wrapper').find('tr').mousedown(function(event) {
Upvotes: 0
Reputation: 749
Your selector seems to be allright. Maybe you should use .click instead of .mousedown Also, have you put the event bindings within a document load function? Besides, I think it's weird you don't have a table element. But that shouldnt be the problem.
Create a jsfiddle if you need us to give a better look at it.
Upvotes: 0
Reputation: 284
You already given id attribute to each row so easily you can access each row by using jquery.
Upvotes: 0