The code below works but i always get the value of the last button in the table. How do i log the correct table count from each button. console.log always gives the value of the last button.
<!DOCTYPE html>
<html>
<head>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click "add row" to add several new rows, then click "show count"</p>
<button type="button" onclick="addTr()">add row</button>
<table id="myTable">
</table>
<script>
function showCount(trCount) {
console.log("trCount = " + trCount);
}
var trCount = 0;
function addTr() {
var table = document.getElementById("myTable");
var tr = table.insertRow(trCount);
var td0 = tr.insertCell(0);
td0.innerHTML = (trCount + 1);
var td1 = tr.insertCell(1);
td1.innerHTML = '<input type="button" value="Show Count" onclick="showCount(trCount)">';
trCount++;
}
</script>
</body>
</html>
Tyr this code:
function showCount(trCount){
console.log("trCount = "+trCount);
}
var trCount = 1;
function addTr() {
var table = document.getElementById("myTable");
var tr = table.insertRow(trCount-1);
var td0 = tr.insertCell(0);
td0.innerHTML = trCount;
var td1 = tr.insertCell(1);
// Pass trCount as an argument to showCount
td1.innerHTML = '<input type="button" value="Show Count" onclick="showCount(' + trCount + ')">';
trCount++;
}