Reputation: 228
I have a table
, something like the following
<table>
<tr>
<td onclick="toggleRow(this)">some text</td>
<td onclick="toggleRow(this)">some text</td>
<td onclick="toggleRow(this)">some text</td>
<td>
<input type="checkbox" onclick="toggleRow(this)" value="1" />
</td>
</tr>
</table>
Javascript:
<script>
function toggleRow(obj) {
console.log(obj);
}
</script>
When I click on td
I get the following outputs
<td onclick="toggleRow(this)">some text</td>
and when I click on checkbox
, i get the following output
<input type="checkbox" onclick="toggleRow(this)" value="1" />
How can I get
<td onclick="toggleRow(this)">some text</td>
when I click on checkbox
?
Thanks.
Upvotes: 0
Views: 30
Reputation: 82241
You can traverse to closest td obj using .closest
selector:
closest:For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
function toggleRow(obj) {
console.log($(obj).closest('td')[0]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function toggleRow(obj) {
console.log($(obj).closest('td')[0]);
}
</script>
<table>
<tr>
<td onclick="toggleRow(this)">some text</td>
<td onclick="toggleRow(this)">some text</td>
<td onclick="toggleRow(this)">some text</td>
<td>
<input type="checkbox" onclick="toggleRow(this)" value="1" />
</td>
</tr>
Upvotes: 1