I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick
attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax onclick='function_name'
, I keep encountering the error message "editRow is not defined" and the button doesn't trigger any action when clicked. It seems like the HTML is interpreting the single quote I entered in the cell's text as double quotes. I'm unsure of what is causing this problem.
var info = [{
"firstName": "aaa",
"lastName": "A"
}, {
"firstName": "bbb",
"lastName": "B"
}, {
"firstName": "ccc",
"lastName": "C"
}];
function display(info) {
var table=document.getElementById("table");
var Length=info.length;
for(var i=0; i<info.length; i++)
{
var row = table.insertRow(i+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = info.[i].firstName;
cell2.innerHTML = info.[i].lastName;
var editButtonHTML = "<input type=button value=Edit class=edit id=edit-button"+(i+1)+" onclick=\'editRow("+(i+1)+")\'>";
cell3.innerHTML=editButtonHTML;
}//end for
function editRow()
{
console.log("inside editRow "+(i+1));
}
//console.log(table.innerHTML);
}//end display
The solution provided by @Rohit Kumar works when running the code in Firefox browser. But when running it in the addon extension using jpm, it gives:
ReferenceError: editRow is not defined
Also, when I print the HTML code in the table, I see double quotation marks instead of singles.
I also attempted adding an event listener after the button element, but unfortunately, it did not work as expected.
butId="edit-button"+(i+1);
console.log("button id is: "+butId);
document.getElementById(butId).addEventListener('click',editRow);