Reputation: 7396
Good Evening, i want to get all the data from the row that the user clicks on, so i tried this script, it gets the row id but it doesn't get the data exists in that row, i push every data in that row to an array for further uses:
function findRowNumber() {
var rowIdx;
var rowData = new Array();
var table = document.getElementById('product_table');
var rows = table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow = rows[rowIdx];
for (j = 1; j < selectedRow.length; j++) { // it doesn't enter that loop
rowCellValue = selectedRow.cells[j].value;
rowData.push(rowCellValue);
alert("Value " + rowCellValue);
}
}
}
}
Upvotes: 0
Views: 7695
Reputation: 104840
If the data in the cells is text,
it may be simpler to retrieve with textContent(or innerText).
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
<style>
table{border:3px ridge #c0c0c0;border-collapse:collapse;}
th, td{border:1px solid black}
</style>
<script>
function findRowNumber(){
var rowIdx;
var rowData= [];
var table= document.getElementById('product_table');
var rows= table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for(i= 0;i<rows.length;i++){
rows[i].onclick= function(){
rowIdx= this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
alert("Row #" +rowIdx+'. '+ rowData);
}
}
}
</script>
</head>
<body>
<h1> Retrieve Row Data</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "findRowNumber()">
Click to initialize</button> </p>
<table id="product_table" style="width:300px">
<tbody>
<tr> <td> a</td> <td> 1</td> </tr>
<tr> <td> b</td> <td> 2</td> </tr>
<tr> <td> c</td> <td> 3</td> </tr>
<tr> <td> d</td> <td> 4</td> </tr>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>
Upvotes: 0
Reputation: 26739
selectedRow is populated after you click the row, while you are trying to loop trough it after binding the click handler, but before the actual click. You have to move that code in the click handler
Upvotes: 2