Yehuda Gutstein
Yehuda Gutstein

Reputation: 381

Unable to trigger buttons created by php

My php script creates a table with a list of courses and buttons in each row. Each set of buttons should obviously do the same thing, but for that particular row. Each row contains a button with class='add_button', class='wait_button' and class='detail_button'. The value for each button is the courseID of that particular row. This script is sent back to the main page via ajax, and inserted in the middle of the page.

When I click on one of these buttons, I would like to trigger a basic jquery event to test that each button is properly set. However, my current code does not seem to be working. I saw this in a similar post, tried the solution, and still got nothing. Therefore, I have left my initial script. Thank you for any and all suggestions.

courseDb.php:

while($row = mysqli_fetch_array($findCourses)){
echo "<tr>".
"<td><h3>" . $row['courseDept']. $row['courseNumber']. "-".$row['courseSection']."</h3>".
"<p>" . $row['courseName']."</p>".
"<td><p>Course Capacity: " . $row['courseSize']."/". $row['courseCurrent']."</p>".
"<p>Waitlist Capacity: " . $row['waitSize']."/". $row['waitCurrent']."</p></td>".
"<td><button class='add_button' value='".$row['courseID']."'>Add to Schedule</button></td>".
"<td><button class='wait_button' value='".$row['courseID']."'>Add to Waitlist</button></td>".
"<td><button href='#coursesDetailStud'  class='detail_button'  value=".$row['courseID'].">View detail</button></td>".
"</tr>";        

}

courses.php:

$(".add_button").click(function(){
var clicked = $(this);
alert(clicked.val());
});

Upvotes: 0

Views: 40

Answers (1)

luiges90
luiges90

Reputation: 4598

This script is sent back to the main page via ajax, and inserted in the middle of the page.

It seems to me that these rows (and the buttons) are returned by AJAX and is created after the page has been loaded.

As usual, any script placed directly in PHP or HTML files are executed on page load. If you simply use click method, it only bind the events on the elements already existing in the page, and have no effect if the HTML elements are added later by AJAX and DOM manuipulation.

You will need on with delegation, to make your event be bound even for elements loaded afterwards. (Assuming the parent table exists in the HTML/PHP)

$('table').on('click', '.add_button', function(){
    //your code
});

Upvotes: 2

Related Questions