I would like to generate an HTML table with dynamic content in PHP, and add an onclick event on a cell of each row, to trigger an action depending on that row.
How to achieve that ?
Here is my example : I have a table which prints data from a database. Table is made of 3 columns. Columns 1 and 2 hold name and surname and column 3 refers to a comment. Third column says "Comment exists" or "No comments", depending on whether a related comment exists or not.
The goal is to pop up a small window when user clicks on the third column, to show the given comment.
Here is an example of a table, and what I have tried so far :
<table border=1>
<tr>
<th>ID</th>
<th>Vardas</th>
<th></th>
</tr>
<?php while($row = mysql_fetch_array($res)) : ?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['vardas'] ?></td>
<td><?php echo $row['gedimas'] ?></td>
</tr>
<?php endwhile; ?>
</table>
How do I add on click event for the $row['gedimas']
line, to display a full comment from database ?
You can place an "onclick" event directly in PHP :
<td <?php echo "onclick='displayComment(".$id.")'" ?> >
About the general structure of opening a window, you can build the table pretty easily, and then have another page for displaying the comment if there is.
Code for the table :
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Has comment ?</th>
</tr>
<?php
for( $i = 0; $i<count($database_data); $i++){
$item = $database_data[$i];
?><tr>
<td><?php echo $item[0] ?></td>
<td><?php echo $item[1] ?></td>
<td <?php
echo "onclick='displayComment("
echo $item[0].", ".$item[1]
echo ")'"?>
><?php echo $item[2] ? "Comment exists" : "No comments" ?></td>
</tr>
}
Then you would need to include a javascript file with the following code :
function displayComment(name, surname) {
window.open(
"display_comment.php?name="+encodeURI(name)+"&surname="+encodeURI(surname),
"_blank",
"height=200, width=300"
}
And lastly, you would need your display_comment.php
page, whose essence would be :
// get comment from database using data in $_GET["name"] and $_GET["surname"]
Comment from <?php echo $_GET["name"]." ".$_GET["surname"] ?> :
<br>
<?php echo $comment_retrieved_from_database ?>
An alternative would be to only record the id of the comment in the HTML code, and then add the onclick events in javascript.
The php code for the cell would be as follows :
<td <?php echo "data-comment-id='$id'" ?> >
And you would add the onclick events in javascript that way :
var tableCells = document.querySelectorAll("td[data-comment-id]");
for(var i=0; i<tableCells.length; i++){
var cell = tableCells[i];
var commentId = cell.getAttribute("data-comment-id");
cell.addEventListener("click", function(){openPopup(commentId);});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments