I added a button inside my innerHTML table, the button on the first row work, but those follow is not working.
HTML:
<p id="stat_tbl"></p>
Javascript:
let tbl = document.getElementById("stat_tbl")
var txt = ""
txt += "<table>"
txt += "<tr><th>Name</th><th>Code</th></tr>"
for(x in obj) {
txt += "<tr><td> + obj[x].name + </td>"
txt += "<td><button type='' id='btnclick' onclick='tes()' value='" + obj[x].code + "'>Show Code</button></td></tr>"
}
txt += "</table>"
tbl.innerHTML = txt
I tried:
let btn = document.createElement("button")
txt += "<td>" + btn + "</td></tr>"
tbl.appendChild(btn)
but the Output is = [object HTMLButtonElement]
There are some way to resolve this problem in you code.
Bases on, not very efficient, but works, approach where onclick
handler are set inline you may pass the event
to handle click. And then take reference to button via event.target
.
Avoid set the same id
for numbers of elements like id='btnclick'
, there is no sense.
let tbl = document.getElementById("stat_tbl")
let obj = {a: {name: 'aObj', code: 'A'}, b: {name: 'bObj', code: 'B'}};
var txt = ""
txt += "<table>"
txt += "<tr><th>Name</th><th>Code</th></tr>"
for(x in obj) {
txt += "<tr><td>" + obj[x].name + "</td>"
txt += "<td><button type='' onclick='tes(event)' value='" + obj[x].code + "'>Show Code</button></td></tr>"
}
txt += "</table>"
tbl.innerHTML = txt
function tes(ev) {
console.info(ev.target.value);
}
<p id="stat_tbl"></p>