Home > Mobile >  Get the value of a particular element with JavaScript that is looped with PHP
Get the value of a particular element with JavaScript that is looped with PHP

Time:03-04

$sql = "SELECT * FROM users ";
                  $res = query($sql);
                  foreach($res as $row) {
                  
                  ?>
                  <tbody>
                    <tr>
                      <td><?php echo $row['name'] ?></td>
                      <td><?php echo $row['user'] ?></td>
                      <td><img src= '<?php echo $row['pix'] ?>' alt='image' ></td>
                      <td><?php echo $row['email'] ?></td>
                      <td><?php echo $row['phone'] ?></td>
                      <td>
                      <span >
                      <input id="username" hidden value="<?php echo $row['name']; ?>"> 
                        <a onclick="check()"><i  style="color: green; cursor: pointer;"></i></a>
                        <a><i onclick="del()"  style="color: #001737; cursor: pointer ;"><p id="del" hidden><?php echo $row['name']; ?></p></i></a>
                        <a onclick="email()"><i  style="color: #001737; cursor: pointer;"></i></a>

Above is a loop from my db. Onclick of some icons, I want javascript to perform some actions. To perform these actions, I have to pick <?php echo $row['name'] ?> and I have got that from <input id="username" hidden value="<?php echo $row['name']; ?>">. The issue I am having now is that JavaScript will only pick the first id. This is because <input id="username" hidden value="<?php echo $row['name']; ?>"> is being looped and Javascript will pick the first.

I have tried many methods but didn't work. Please what can I do?

CodePudding user response:

in hidden field append user_id with 'username' like this

<input id="username<?php echo $row['user_id']; ?>" hidden value="<?php echo $row['name']; ?>">

and in onclick method pass user_id like this

<a onclick="check(<?php echo  $row['user_id']; ?>)">

and then in javascript you can select that value

function check(id){
    var data=$('#username' id).val();
}
  • Related