How To Append A Button With Onclick Event That Fires A Function To A Table Cell
I am struggling with adding a button to a table cell. The button should fire a function by calling its name and sending it two arguments. Can anyone show a simple example. This is
Solution 1:
use innerHTML
not value
this is solution for button editbtn.innerHTML = "EDIT";
to add click event editbtn.onclick = (function(i){ return function(){ editRow(i+1)}})(i);
We need to bind i value to that onclick function. the above function does that.
var info = [{
"firstName": "aaa",
"lastName": "A"
}, {
"firstName": "bbb",
"lastName": "B"
}, {
"firstName": "ccc",
"lastName": "C"
}];
var table = document.getElementById("table");
var storageLength = 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 editbtn = document.createElement('button');
editbtn.type= "button";
editbtn.className= "editbtn";
editbtn.id= "button-"+(i+1);
editbtn.value= "Edit";
editbtn.innerHTML = "EDIT";
editbtn.onclick = (function(i){ returnfunction(){ editRow(i+1)}})(i);
cell3.appendChild(editbtn); // Append <button> to <body>
} //end forfunctioneditRow(rowindex)
{
console.log("inside editRow "+(rowindex));
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="table"border='1'><tr></tr></table>
Solution 2:
In order to solve the issue of editRow printing out the correct row number, you need to use some form of closure. (How do JavaScript closures work?)
What's happening now is that the function's parameter is bound to i
, which changes value to 4 by the end of the loop, so every function will be passed 4 as a parameter.
A simple edit would be:
editbtn.onclick = (function(index) {
editRow(index);
})(i);
Solution 3:
If you want to add a edit button to each table cell, you can do something like this
$('.tableCell').each(function() {
$target = $(this)
var content = $target.html()
$button = $('<button>Edit content✏️</button>')
$target.append($button);
$button.on('click', function(e){
e.preventDefault()
e.stopPropagation()
doMagic(content)
})
})
Post a Comment for "How To Append A Button With Onclick Event That Fires A Function To A Table Cell"