0

I want to make the copy button copy the value of user, but the problem is the button copied only the value of first user. When move to second user, it remain copied the valued of the first user. Here are my code.

<?php
    require_once('connection.php');
    $sql = "SELECT ftname, menu, longlan FROM 
    ownerinfo";
    $result = $con->query($sql);

    if ($result) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $a=1;
            $long[$a]=$row["longlan"];

            echo "Food Truck: " . $row["ftname"]. " 
            <br>Menu: " . $row["menu"].  " 
            <br>Longitude Latitude: <input id='he ' 
            value='".$long[$a]."'></input><button 
            onclick='myFunction()'>Copy</button><br>
                                <a 
            href='https://maps.google.com/'>Maps</a> 
            <hr>";

            $a=$a+1;
        }          
    } else {
        echo "0 results";
    } 
?>

<script>
  function myFunction() {
  var copyText = document.getElementById("he");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
  }
user1506104
  • 6,554
  • 4
  • 71
  • 89
Syafiq
  • 1
  • 1
  • the problem is you have multiple inputs with a single `id`. The one that `getElementById("he")` will find is the first instance of `he`, which is the first user, so every time you *copy*, it will always get the first input – Carl Binalla May 28 '18 at 03:18

1 Answers1

0

Considering your loop outputs an ID, your JavaScript will only ever be able to target the first instance of that ID (as multiple IDs are considered invalid markup).

To correct this, output classes from your PHP instead:

<input class='he' value='".$long[$a]."'>

And loop over each of the classes in your JavaScript:

const copyText = document.getElementsByClassName("he");
for (let i = 0; i < copyText.length; i++) {
  copyText[i].select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText[i].value);
}
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71