Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Working with Numbers and Math > Summing All Numbers in a Table Colum...

recipe 4.7. Summing All Numbers in a Table Column

4.7.1. Problem

You want to traverse all of the values in a table column, convert the values to numbers, and then sum the values.

4.7.2. Solution

Traverse the table column containing numeric values, convert to numbers, and sum the numbers:

var sum = 0;

 // use querySelector to find all second table cells
 var cells = document.querySelectorAll("td:nth-of-type(2)");

 for (var i = 0; i < cells.length; i++)
      sum+=parseFloat(cells[i].firstChild.data);

4.7.3. Discussion

Both global functions parseInt and parseFloat convert strings to numbers, but parseFloat is more adaptable when it comes to handling numbers in an HTML table. Unless you’re absolutely certain all of the numbers will be integers, parseFloat can work with both integers and floating-point numbers.

As you traverse the HTML table and convert the table entries to numbers, sum the results. Once you have the sum, you can use it in a database update, print it to the page, or pop up a message box, as the solution demonstrates.

You can also add a sum row to the HTML table. Example 4-1 demonstrates how to convert and sum up numeric values in an HTML table, and then how to insert a table row with this sum, at the end. The code uses document.querySelectorAll, which uses a CSS selector, td + td. This selector finds all table cells that are preceded by another table cell.

Example 4-1. Converting table values to numbers and summing the results

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Accessing numbers in table</title>

<script type="text/javascript">
//<![CDATA[

window.onload=function() {

   var sum = 0;

   var dataTable = document.getElementById("table1");

   // use querySelector to find all second table cells
   var cells = document.querySelectorAll("td + td");

   for (var i = 0; i < cells.length; i++)
      sum+=parseFloat(cells[i].firstChild.data);

   // now add sum to end of table
   var newRow = document.createElement("tr");

   // first cell
   var firstCell = document.createElement("td");
   var firstCellText = document.createTextNode("Sum:");
   firstCell.appendChild(firstCellText);
   newRow.appendChild(firstCell);

   // second cell with sum
   var secondCell = document.createElement("td");
   var secondCellText = document.createTextNode(sum);
   secondCell.appendChild(secondCellText);
   newRow.appendChild(secondCell);

   // add row to table
   dataTable.appendChild(newRow);

}

//--><!]]>
</script>
</head>
<body>
<table id="table1">
   <tr>
      <td>Washington</td><td>145</td>
   </tr>
   <tr>
      <td>Oregon</td><td>233</td>
   </tr>
   <tr>
      <td>Missouri</td><td>833</td>
   </tr>
</table>
</body>
</html>

					  

Being able to provide a sum or other operation on table data is helpful if you’re working with dynamic updates via an Ajax operation, such as accessing rows of data from a database. The Ajax operation may not be able to provide summary data, or you may not want to provide summary data until a web page reader chooses to do so. The users may want to manipulate the table results, and then push a button to perform the summing operation.

Table rows are simple to add, as long as you remember the steps:

  1. Create a new table row using document.createElement("tr").

  2. Create each table row cell using document.createElement("td").

  3. Create each table row cell’s data using document.createTextNode(), passing in the text of the node (including numbers, which are automatically converted to a string).

  4. Append the text node to the table cell.

  5. Append the table cell to the table row.

  6. Append the table row to the table. Rinse, repeat.

If you perform this operation frequently, you’ll most likely want to create functions for these operations, and package them into JavaScript libraries that you can reuse. Also, many of the available JavaScript libraries can do much of this work for you.

4.7.4. See Also

See more on JavaScript libraries in Chapter 17. View more demonstrations of creating web page components in Chapter 12. The document.querySelectorAll is one of the new Selectors API methods, and won’t work with older browsers. It is not supported in IE7. For new browsers, there may also be restrictions on its use. More examples and discussion of the Selectors API can be found in Section 11.5.