John Doe
John Doe

Reputation: 53

jQuery dynamic table click

I am running in a problem with jQuery I can not fix. I am generating a table body by appending table rows dynamically using jQuery. I created an example demonstrating the issue:

var i = 0;

function addStuff() {
  $('#table-body').append("<tr class=\"log-entry-row\"><td class=\"description\">item" + i + "</td><td class=\"sometext\">item" + i + "</td></tr>");
  i++;
}


$("#table-body").on("click", ".log-entry-row", function() {
  var text = $(this).find(".sometext")[0].innerHTML();
  console.log($(this).find(".sometext")[0].innerHTML);
  $('#clickedCell').innerHTML(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="table-body">

  </tbody>
</table>

<button onclick="addStuff();">ADD ENTRY</button>
<span id="clickedCell"></span>

https://codepen.io/anon/pen/WKOzYN

I can not get it to work no matter what I try. The stupid thing about is that logging it to console works fine.

Can someone please explain what is going on?

Upvotes: 0

Views: 54

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're attempting to call innerHTML() on a jQuery object, which does not have that function. Use jQuery's html() method instead:

var i = 0;

$('button').click(function() {
  $('#table-body').append('<tr class="log-entry-row"><td class="description">item' + i + '</td><td class="sometext">item' + i + '</td></tr>');
  i++;
});

$("#table-body").on("click", ".log-entry-row", function() {
  var text = $(this).find(".sometext").html();
  $('#clickedCell').html(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="table-body"></tbody>
</table>

<button>ADD ENTRY</button>
<span id="clickedCell"></span>

Also note that if you use ' to delimit a string then you don't need to escape the " characters within that string. It's also much better practice to attach your event handlers unobtrusively instead of using the outdated on* event attributes.

Upvotes: 1

flyingfox
flyingfox

Reputation: 13506

The problem is caused by

$('#clickedCell').innerHTML(text)

innerHTML is a property,not a method,you can use html()instead.

$('#clickedCell').html(text)

Upvotes: 1

Related Questions