0

I'm having a difficult time manipulating dynamic content through either Javascript or JQuery. I send a few parameters through a $.post request. I return the data from a PHP page as echoand set it as the html for a static html div element.

$.post("test-new.php", {owners:"dynamic"}, function(data) {
   $("#weekView").html(data);
}

When this is run the static html element is populated with the returned post data fine. The data includes a dynamically created table and a button to add a row to the table. The reason I included the table in the php and didn't make it static is because there are several tables created depending on the $.post parameters.

The problem is noticed when I attempt to add a row to a newly created table using a dynamic button. The dynamic button has an onclick attribute that triggers a static Javascript or JQuery function.

Echoed html for table from PHP page:

echo "<table class='tbl-project' id='".$row4['task_id']."1'><tr><td>...</td></tr></table>"...

Echoed html for button from PHP page:

echo "<button type='button' class='btn btn-primary' value='".$row4['task_id']."1' 
onclick='addTask(this.value)'>New Task</button>";

I then attempt to add a row to the table using JQuery:

function addTask(e) {
    console.log(e);
    $('#' + e + '1 tr:last').after('<tr><td>...</td></tr>');
}

When I click the dynamic button the console displays the correct value but no rows are added. Any ideas what all I'm doing wrong?

PSFord
  • 29
  • 1
  • 6
  • I'm not exactly clear as to how that answer is exactly the same - but I'll take your word for it. Any idea how to adjust my function to get the performance I'm looking for? – PSFord Jan 07 '16 at 15:40
  • Because you're adding DOM elements dynamically you have to rebind or use event delegation. It would be easier if you didn't use inline JS and just used pure JS or jQuery. – Jay Blanchard Jan 07 '16 at 15:42
  • 1
    Thank you, I was able to find my mistake through the suggested answer. Just to clarify, I had a couple of errors. Mainly in my echo I appended a '1' to the id of the table to ensure that it was unique. But, in error, I also appended the 1 to in the jquery function. So the element my function was searching for never existed (so dumb) – PSFord Jan 07 '16 at 16:10
  • Awesome, glad I was able to help. If the answer there helped, please consider upvoting. – Jay Blanchard Jan 07 '16 at 16:14

0 Answers0