How can I get values of TDs inside an HTML table?
i.e.
| ID | cell 1 | cell 2 |
| 1 | aaaa | a2a2a2 |
| 2 | bbbb | b2b2b2 |
| 3 | cccc | c2c2c2 |
So now if I click on the cell value: "bbbb" I want to get all the values of selected row:
$id='2'; $cell_1='bbbb'; $cell_2='b2b2b2';
NOTE: I'd like to use JavaScript and not jQuery.
You can use event.target.innerText for javascript and $(event.target).text() for jQuery, jQuery is preferred solution as it handles cross browser competibilities.
Using only javascript
Live Demo
Html
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Javascript
function myFun(e){
alert(e.target.innerText); //current cell
alert(e.target.parentNode.innerText); //Current row.
}
Using jQuery
Live Demo
Html
<table id="tableID" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Javascript
$('#tableID').click(function(e){
alert($(e.target).text()); // using jQuery
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With