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:


readtable.html
<html>
<head>
<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);
     }


</script>

</head>


<body>

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

    <tr>
        <td>A100</td>
        <td>Computer</td>
        <td>30000</td>       
    </tr>
    <tr>
        <td>A101</td>
        <td>Printer</td>
        <td>2000</td>       
    </tr>
    <tr>
        <td>A102</td>
        <td>Keyboard</td>
        <td>200</td>       
    </tr>
    <tr>
        <td>A103</td>
        <td>Mouse</td>
        <td>150</td>       
    </tr>

    <tr>
        <td>A104</td>
        <td>Speaker</td>
        <td>1500</td>       
    </tr>

</table>

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

</body>
</html>



No comments:

Post a Comment