How To Grab The Values From An HTML Table's Cells Using JavaScript
I'm trying to grab the cell values from an HTML table so that I can save them into a MySQL table via a call to PHP. I'd like to use JavaScript rather than jQuery. I'm giving each
Solution 1:
Use the innerText
property for the td
. Here's a fiddle that shows how to use it.
HTML
<table>
<tr>
<td id="1">Bla</td>
<td id="2"><input id="txt" />Ble</td>
</tr>
</table>
JavaScript
var td = document.getElementById('1');
alert(td.innerText);
var td2 = document.getElementById('2');
alert(td2.innerText);
Solution 2:
How to grab cell values from a table?
Update to address Elliots comment
See how to grab the cell value (innerText and data-value) in my new demo
In the table the attribute data-value
is used to store some data (2B, 3C,..).
<table id="t2">
<thead>
<tr id="tr1"><th>Student Name<th>Course</tr>
</thead>
<tbody>
<tr id="tr2"><td data-value="2B">Bert2 <td>Economics </tr>
<tr id="tr3"><td data-value="3C">Clyde3 <td>Chemics </tr>
<tr id="tr4"><td data-value="4D"> <td>Digital Art</tr>
<tr id="tr5"><td data-value="5E">Ernest <td>Ecmoplasma </tr>
</tbody>
</table>
With jQuery and the right selector you can iterate over each cell:
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
// iterate over each row in table with id t2 in the table-body (tbody)
$('#t2 tbody tr').each(function(index){
// copy the text into an array
cellInnerText.push($(":first-child", $(this)).text());
//copy the data-value into an array
cellValue.push($(":first-child", $(this)).attr('data-value'));
});
// show content of both arrays
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
Solution 3:
Alert the innerHTML of the first cell in the table's first row
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to alert the innerHTML of the first cell (td element with index 0) in the table's first row.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);
}
</script>
</body>
</html>
Solution 4:
Place IDs on Your inputs with some pattern. for example <input type="text" id="input_0_0" name="whatever" />
where 0
is row and second 0
is column and then instead your alert type
v = document.getElementById('input_'+row+'_'+col).value;
It should help You get rolling now
Post a Comment for "How To Grab The Values From An HTML Table's Cells Using JavaScript"