0

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);
}
1
  • Please add more code, where did you call this function. Commented Dec 12, 2019 at 22:01

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

entry is an JSON object and I want to pass the entire object. The deleteEntry function is an ajax call to a rest server to delete it from a MySQL database.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.