How to append a button with onclick event that fires a function to a table cell

javascript add onclick event dynamically
how to add click event to dynamically added html element in typescript
how to add onclick event in javascript dynamically for button
how to bind click event in jquery for dynamically added html element
event binding on dynamically created elements javascript
event delegation javascript
click event for dynamically created button jquery
addeventlistener

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 what I tried to do but it has two problems: 1) the button appear so small almost invisible. 2) The event never fires (also the function is big and I want it to be called by its name because I want to place its body outside).

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.onclick = 'editRow(i+1)';
cell3.appendChild(editbtn);                    // Append <button> to <body> 
} //end for

function editRow(rowindex)
{
    console.log("inside editRow "+(rowindex));
}

HTML:

<table id="table" border='1'>
  <tr></tr>
</table>

EDIT: If you can provide me with a solution for using: var editButtonHTML = "

(i + 1) + " onclick='editRow(" + (i + 1) + ")'>";
cell3.innerHTML=editButtonHTML;

That would be better as this method makes the button appear in the normal size. But my only problem is that I'm not getting the function fired. This problem appears in firefox addon using jpm. With innerHTML, the event get fired when I open the page normally in the browser. I suspect that they syntax should be 'onclick=..' with single quotation not double. When I inspect the HTML, it automatically makes the single quotations as doubles even if I use \ to escape them.

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){ return function(){ editRow(i+1)}})(i);
cell3.appendChild(editbtn);                    // Append <button> to <body>
} //end for

function editRow(rowindex)
{
    console.log("inside editRow "+(rowindex));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" border='1'>
  <tr></tr>
</table>

Attaching event handlers to dynamically created JavaScript , 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​);. Using onclick to create a dropdown button: // Get the button, and when the user clicks on it, execute myFunction. document.getElementById("myBtn").onclick = function() {myFunction()}; /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */.

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);

Handling Events :: Eloquent JavaScript, Let's say we have a list of items that you could click on to toggle/add a class Table of contents To create an onclick function is simple, we just target our element, and setup a click handler: Taking our knowledge from above, we can loop through our HTML and attach the event handler to each <li> tag. in my datatable i have 2 rendered button links in each row, each to perform a specific function. what i want to do is have an on click event for each button, so when each button is clicked, some of the row data is used in each function

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)
  })
})

Event delegation, The addEventListener method allows you to add any number of handlers so that it is <button>Click me any way you want</button> <script> let button = document. Pressing a mouse button causes a number of events to fire. indication of progress (by highlighting part of a table of contents or showing a page number). In the demo I’ve setup, you’ll see the existing list of items, give one or two a click and watch the text change and a nice icon appear. Voila! Now, the next step is to create your own element, which I’ve created a nice little script and small form to do exactly that. Simply type a word into the field input, and generate your element. The

Smashing jQuery, Brown Tranquility, South Fire Orange Fame, Southeast Wood Green table . onclick = function ( event ) { let td = event . target . closest ( 'td' ) ; // (1) if The HTML structure is flexible, we can add/remove buttons at any time. Hi, I created a table by the code below. Now I want to add an onclick event to any cell. How can I modify the code? That means that if I click any cell, it will display something.

JavaScript Tutorial: The Basics, Table 4.2 summarizes each mouse event and its function. with bind() Event Name Event Function click Fires when mouse button is pressed If you use JavaScript to create a click event, you add the onClick action directly to the element. <a href:”product.html” onClick:”myFunction() ;”>Paper Towels</a> jQuery uses a  An event listener always has the clicked element as target and the element, that the listener was bound to as context. long story short, when you click on the table cell, the listener's context is the cell and hence you have access to the cell content.

GlobalEventHandlers.onclick, 2.5 Example 5: User-defined Functions and onclick Event Handler The alert(​aString) function puts the aString on a pop-up box with a OK button. onmouseout : fires when the user points the mouse pointer at/away from the HTML element. by positioning the mouse pointer on the variable; or add the variable to "watch". Javascript Element How to - Handle click event for table cell td. Back to Table Cell ↑ Question. We would like to know how to handle click event for table cell td. Answer!--f r o m w w w. j a v a 2 s. c o m--> <!

Comments
  • Try: editbtn.onclick = editRow.bind(this, i + 1);
  • Thanks. But, what about the function body? I am trying function editRow(n) { console.log("inside edit row"+ n); }. It works but I am not sure if it correc? how to send two arguments and the function body receives one? I just want to make sure that it won't cause me other problems later.
  • But it always print the last i in the loop. E.g. it will always print inside editRow 4. But I want it to be depends on which row I press edit. E.g. row 1 should print ``inside editRow 1`, etc.
  • @user7945230 it took me while to fix that. its working now please check
  • Thanks but still one mroe issue. How to move the function body out? I tried: editbtn.onclick=editRow(i+1). I tried this: editbtn.onclick = editRow(i+1); function editRow(i+1) { console.log("inside index: "+i+1);. But did not work. }(i+1);. But did not work.
  • How can I move the function body out? so I just call editbtn.onclick=editRow(i+1). I tried this: editbtn.onclick = editRow(i+1); function editRow(i+1) { console.log("inside index: "+i+1); }(i+1);. But did not work.
  • Use the code snippet provided above as is. editRow is still defined outside of the onclick assignment.
  • It did not work at least for firefox addon. But it might work the file opened from a browser. I accepted @Dinesh answer's. It worked with me.