How to Fill a Table Cell With JavaScript

Manipulating HTML tables requires JavaScript. The HTML Document Object Model, or DOM, gives developers the ability to use JavaScript to change the "innerHTML" property of any element on a Web page including table cells. The innerHTML property generates the content you see on a Web page. You might change a table cell's innerHTML property, for example, when a user clicks a "Show Price" button. This action would cause a price to appear in the cell. Once you understand how to use the DOM to locate a cell, you can fill it with any value instantly.

Instructions

    • 1

      Open an HTML document and paste the following code into the document's "body" section:

      <table id="testTable1" border=1>
      <tr>
      <td>no value</td>
      <td>no value</td>
      </tr>

      <tr>
      <td>no value</td>
      <td>no value</td>
      </tr>

      <tr>
      <td>no value</td>
      <td>no value</td>
      </tr>

      </table>
      <input type="button" value="Fill Cell" onclick="return fillCell('testTable1', '2','1', 'Test Value')" />

      This code creates a new table. The table, whose "id" is "testTable1" contains three rows with two cells per row. The button calls a JavaScript function named "fillCell." That function locates a cell and fills it with the value "Test Value" passed in the button click event.

    • 2

      Paste the code shown below into your document's "script" section:

      function fillCell(table, targetRow, targetCell, fillContents) {

      var tableObj = document.getElementById(table);
      var selectedRow = tableObj.rows[targetRow-1];

      var selectedCell = selectedRow.cells[targetCell-1];
      selectedCell.innerHTML = fillContents;
      }

      This function receives the table ID, target row and target cell passed by the button click. It also receives that value you wish to use to fill the target cell. The code then locates the desired cell within the target row and sets its innerHTML property to the value stored in the fillContents variable.

    • 3

      Save your document and view it in a browser. Click the button to run the JavaScript function. It locates the first cell in the second row and fills the cell with the words "Test Value."

Tips & Warnings

  • Remove the contents of a cell by setting the value of cellContents to " " before calling the fillCell function. This sets the innerHTML value of the target cell to blanks.

Related Searches:

References

Resources

Comments

Related Ads

Featured