[javascript] How to get html table td cell value by JavaScript?

I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not know how to access the cell value in the Javascript function.

The value of the cell is actually the index of a record and it is hidden in the table. After the record key is located I can retrieve the whole record from db.

How to get the cell value if I do not know the row index and column index of the table that I clicked?

This question is related to javascript html-table cell

The answer is


.......................

  <head>

    <title>Search students by courses/professors</title>

    <script type="text/javascript">

    function ChangeColor(tableRow, highLight)
    {
       if (highLight){
           tableRow.style.backgroundColor = '00CCCC';
       }

    else{
         tableRow.style.backgroundColor = 'white';
        }   
  }

  function DoNav(theUrl)
  {
  document.location.href = theUrl;
  }
  </script>

</head>
<body>

     <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

            <% for (Course cs : courses){ %>

            <tr onmouseover="ChangeColor(this, true);" 
                onmouseout="ChangeColor(this, false);" 
                onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                 <td name = "title" align = "center"><%= cs.getTitle() %></td>

            </tr>
           <%}%>

........................
</body>

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

 onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier. It works.


Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

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);
        */
    }
}

_x000D_
_x000D_
var table = document.getElementById('tableID'),_x000D_
  cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
  cells[i].onclick = function() {_x000D_
    console.log(this.innerHTML);_x000D_
  };_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

A revised approach, in response to the comment (below):

You're missing a semicolon. Also, don't make functions within a loop.

This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

_x000D_
_x000D_
function logText() {_x000D_
  console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
  td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

References:


I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var rows = document.getElementById("mytable").rows;
                    for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
                        rows[i].onclick = function() {
                            alert(this.cells[0].innerHTML);
                        }
                    }
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <table id="mytable">
            <tr>
                <td>0</td>
                <td>row 1 cell 2</td>
            </tr>
            <tr>
                <td>1</td>
                <td>row 2 cell 2</td>
            </tr>
        </table>    
    </body>
</html> 

You can use:

<td onclick='javascript:someFunc(this);'></td>

With passing this you can access the DOM object via your function parameters.


This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?

Examples related to cell

Excel doesn't update value unless I hit Enter Excel Define a range based on a cell value Link a photo with the cell in excel VBA setting the formula for a cell Changing datagridview cell color dynamically How to delete Certain Characters in a excel 2010 cell How do I change a single value in a data.frame? Set value for particular cell in pandas DataFrame using index Copying the cell value preserving the formatting from one cell to another in excel using VBA How to get html table td cell value by JavaScript?