简体   繁体   中英

Javascript HTML Table get first column's cell value based on another cell's onclick

I am making a PHP web application and fetching data from MySql into the HTML table below.

<table id = "table" width="500px" cellpadding=2 celspacing=5 border=2 >
 <tr>
   <th>Subject Code</th>
   <th>Subject Name</th>
   <th>Question Paper</th>
 </tr>
 <?php while($row=mysqli_fetch_array($result)):?>
 <tr>
   <td align="center"><?php echo $row['Subject_Code'];?></td>
   <td align="center"><?php echo $row['Subject_Name'];?></td>
   <td align="center"><a href="javascript:showPaper()"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></a></td>
 </tr>
 <?php endwhile;?> 
</table>

Here is the output of the table

在此处输入图片说明

The third column consists of clickable image icons which loads question papers in an iFrame besides it.

I want that when this image is clicked, the cell value of the first column --> 'Subject code' for that particular row is obtained.

Here is the code:

function showPaper(){
   var v;
   //method1 not working
   for(var i=1;i<table.rows.length; i++){
      table.rows[i].onclick = function(){
        rIndex = this.rowsIndex;
        v=this.cells[0].innerHTML;
        alert(v);
      };
   }
  //method 2 not working
  v = $("#table tr.selected td:first").html(); 
  alert(v);            
  /*loc1 path rest of code
  document.getElementById('myiFrame').src = loc1*/;  
}

I require this subject code value as one of the variables in the pdf src path of the iFrame.

But nothing seems to be working, the value in 'v' variable is showing undefined.

How can I make this code work?

you need to use onclick() event to get value of Subject_Code .

Change

<td align="center"><a href="javascript:showPaper()"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></a></td>

With

<td align="center" id="<?php echo $row['Subject_Code'];?>" onclick="showPaper(this.id);"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></td>

And your showPaper() should be

<script>
    function showPaper(id)
    {
        alert(id);
        //Do something
    }
</script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM