1

I tried alert(id) to see if the function is getting the id properly.

When I reload the page the function automatically copies the last row and alerts the id of the last row.

I also tried to take the script; inside php, still not working

<?php
$sql= "SELECT * FROM post ORDER BY id DESC";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$cap = $row['cap'];
echo "<div class='tooltip'>";
echo "<button onclick='myFunction()' onmouseout='outFunc()'>
<span class='tooltiptext' id='myTooltip'>Copy to clipboard</span>
  Copy text
  </button>
</div>
<input type='text' value='$cap' id='$id'>";
?>
<script>
function myFunction() {
  var copyText = document.getElementById("<?php echo $id; ?>");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy");

  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copied: ";
}

function outFunc() {
  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copy to clipboard";
}
</script>
aziz
  • 23
  • 4
  • Have you close while `}` ? – Simone Rossaini Mar 07 '20 at 10:41
  • What's "not working" about it? What specifically happens and what specifically did you expect to happen? What does this emit to the client? It looks like you're re-using `id` values client-side, which makes the markup invalid. It also looks like you're trying to decide bewteen either always using the same `$id` value on the client or defining the same function multiple times on the client, neither of which is likely to do what you want. – David Mar 07 '20 at 10:41

1 Answers1

1

There may only be one function with a particular name on the top level at any one time. Your later declarations of myFunction inside the loop are overwriting the earlier declarations.

While it'd be possible to fix it by using different function names, it'd be more elegant to avoid IDs entirely, and let the click listener navigate to the input field with DOM methods. Change

<button onclick='myFunction()' onmouseout='outFunc()'>

to

<button onclick='myFunction(this)' onmouseout='outFunc()'>

and use

function myFunction(button) {
  var copyText = button.parentElement.nextElementSibling;
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy");

  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copied: ";
}

If at all possible, also remove the inline handler and attach the listener properly using Javascript instead. Give the buttons a class (or have some other way of selecting it via CSS selectors), then select them with querySelectorAll and iterate over them, attaching the listener to each:

<button class="tooltip-button">
for (const btn of document.querySelectorAll('.tooltip-button')) {
  btn.addEventListener('click', () => myFunction(btn));
  btn.addEventListener('mouseout', outFunc);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320