Mantas Mantas - 2 years ago 89
SQL Question

Add onclick event on a php-generated table cell

I would like to generate an HTML table with dynamic content in PHP, and add an onclick event on a cell of each row, which would 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>
<?php while($row = mysql_fetch_array($res)) : ?>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['vardas'] ?></td>
<td><?php echo $row['gedimas'] ?></td>
<?php endwhile; ?>

How do I add on click event for the $row['gedimas'] line, to display a full comment from database ?

Answer Source

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 :

    <th>Has comment ?</th>
for( $i = 0; $i<count($database_data); $i++){
   $item = $database_data[$i];
       <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>

Then you would need to include a javascript file with the following code :

function displayComment(name, surname) {
      "height=200, width=300"

And lastly, you would need your display_comment.phppage, whose essence would be :

// get comment from database using data in $_GET["name"] and $_GET["surname"]

Comment from <?php echo $_GET["name"]." ".$_GET["surname"] ?> : 
<?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);});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download