Sunday, 26 October 2014

Reading data from an HTML table using JavaScript

This example demonstrates how data in an HTML table can be read using JavaScript which can further be used for submitting to a server side script.

In this example, we first get the reference of the table using  the function call
var table = document.getElementById('productlist'); 
Then loop through each row of the table.
Each time data read from a cell is added to a string separated by a delimiter ( here we used "," ).
Finally the data read is displayed by using alert() function.

Entire code of this example is given below:

<title>Read data from HTML table using Javascript</title>

<script language=javascript>

function readTable() {  
    var table=document.getElementById('productlist');

    for(var i=1; i<table.rows.length;i++){     
        var str_pid=(table.rows[i].cells[0].innerHTML);
        var str_pname=(table.rows[i].cells[1].innerHTML);
        var str_pprice=(table.rows[i].cells[2].innerHTML);

        var str_table_row = str_pid + ", " + str_pname + ", " +  str_pprice  ;

        alert("Row " + i + ":" + str_table_row);




<h3>Product List</h3>
<table id='productlist' border='1' width='30%' >
        <th>Product Name</th>




<input type=button value="Read Table" onclick="readTable()">


No comments:

Post a Comment