cainsr2
cainsr2

Reputation: 55

Calling a function in dynamically created button javascript

I'm trying to create a button with a an onClick that calls a function with the signature deleteEntry(entry). However, I get an error saying that entry is undefined even though I am using it in the same function. I tried adding escape characters but it does not have any effect. Any ideas?

function addToTable(entry) {
  var result = "<tr>"
  result += "<td>" + entry.id + "</td>";
  result += "<td>" + entry.title + "</td>";
  result += "<td>" + entry.url + "</td>";
  result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry + 
    ")\">Delete</button></td>";
  result += "</tr>";
  $("#table").append(result);
}

Upvotes: 0

Views: 178

Answers (2)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

You can create the button as a jQuery object and use the on method to listen to the click event. Then when the event listener is attached append the button to the row like the other elements in the function.

Check the code snippet below to see it in action.

// Dummy entry.
var entry = {
  id: 0,
  title: 'test',
  url: 'http://url.com'
}

// Your AJAX call.
function deleteEntry(entry) {
  console.log(entry);
}

function addEntryToTable(entry) {
  var $id = $('<td>' + entry.id + '</td>');
  var $title = $('<td>' + entry.title + '</td>');
  var $url = $('<td>' + entry.url + '</td>');
  var $button = $('<button class="btn">Delete</button>');
  var $buttonWrap = $('<td></td>');
  var $row = $('<tr></tr>');
  
  // Add 'click' event listener to the button.
  $button.on('click', function(event) {
    deleteEntry(entry);
  });
  $buttonWrap.append($button)
  $row.append($id, $title, $url, $buttonWrap);
  $('#table').append($row);
}

addEntryToTable(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>

Upvotes: 2

GuillaumeB
GuillaumeB

Reputation: 402

If you inspect this button you generated it will probably have the following attribute: onClick="deleteEntry([object Object])

I think what you want is:

result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry.id + ")\">Delete</button></td>";

I guess you have a list variable "entries" somewhere. In the delete function you can find the clicked entry with the inputed Id.

Upvotes: 0

Related Questions