Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML table cells values in a rows by clicking on it

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.

like image 824
Luke Avatar asked Dec 27 '12 08:12

Luke


1 Answers

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
})
like image 166
Adil Avatar answered Oct 20 '22 01:10

Adil