Luke
Luke

Reputation: 513

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.

Upvotes: 9

Views: 36359

Answers (4)

Adil
Adil

Reputation: 148140

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
})

Upvotes: 13

AmGates
AmGates

Reputation: 2123

Hope This helps you. It contains cross browser script.

 <html>
    <head>
    <script type="text/javascript">
    function myFun(e){
    if(!e.target)
        alert(e.srcElement.innerHTML);
    else
        alert(e.target.innerHTML);
    }
    </script>
    </head>
    <body>
    <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>
    </body>
    </html>

Upvotes: 2

Rajesh
Rajesh

Reputation: 3024

Use of jquery will be easy..

$("#tableId").find("td").click(function(event){
   var listOfCell=$(this).siblings();
   for(i=0;i<listOfCell.length;i++){
   alert($(listOfCell[i]).text());
}
}); 

Upvotes: 1

Bhavin Rana
Bhavin Rana

Reputation: 1582

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

from here

Upvotes: 2

Related Questions