Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Javascrypt copy to clipboard function copying just first row

I am a beginner in JavaScript and I do not know how to solve this problem. I have created a table based on my database in MySQL. And now I want to copy one of its cells with the copy button. But my function only copies the first cell. I know I have to give my text different IDs but I do not know how. Here is my code:

             <tr>
                <td class="ttd">&nbsp;</td>
                <td class="ttd"><?php echo htmlentities($f['ID']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Invoice_number']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Invoice_date']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Month']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Space_name']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Company_name']); ?> </td>
                <td class="ttd"><?php echo htmlentities($f['Amount']); ?> </td>
                <div class="tooltip">
                <td class="ttd">
                    <input type="text" style="display:none;" id="Key" value="hhhhhhh.php?token=<?php echo $current_token['token']; ?>">
                    <button onclick="myFunction()" >Copy</button>


                    <script>
                    document.forms[0].addEventListener("submit", function(event){
                            if ( send == 0 ) { event.preventDefault(); }
                            });
    
                    function myFunction() {
                    var hidden = document.getElementById("Key");
                    hidden.style.display = 'block';
                    hidden.select();
                    hidden.setSelectionRange(0, 99999)
                    document.execCommand("copy");
                    alert("Copied the text: " + hidden.value);
                    hidden.style.display = 'none';
                    }
                    </script>
                </td>
                </div>
            </tr>
      
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Problem is you are using the same id over and over. Ids need to be singular in a document. So either you have to give every input a unique id and unique function names or you change your code to look it up based on the button and make it reusable.

You need to reference the element that is beside it. You can either use siblings or you can look at the td and find the element.

Using event delegation so you are not adding a bunch of click handlers to the document.

const tbody = document.querySelector("#myTable tbody");
tbody.addEventListener("click", function (event) {

  // get clicked button
  const btnCopy = event.target.closest(".copy");
  if (btnCopy) {
    copyThis(btnCopy);
  }

});

function copyThis(button) {
  const hiddenInput1 = button.previousElementSibling;
  console.log(hiddenInput1.value);
  
  const hiddenInput2 = button.closest("td").querySelector('input[type="hidden"]');
  console.log(hiddenInput2.value);
  
}
<table id="myTable">
  <tbody>
    <tr>
      <td>
        <input type="hidden" value="1">
        <button type="button" class="copy">Copy</button>
      </td>
    </tr>
      <td>
        <input type="hidden" value="2">
        <button type="button" class="copy">Copy</button>
      </td>
    </tr>
  </tbody>
</table>

If you really want to use inline events

function copyThis(button) {
  const hiddenInput1 = button.previousElementSibling;
  console.log(hiddenInput1.value);
  
  const hiddenInput2 = button.closest("td").querySelector('input[type="hidden"]');
  console.log(hiddenInput2.value);
  
}
<table id="myTable">
  <tbody>
    <tr>
      <td>
        <input type="hidden" value="1">
        <button type="button" class="copy" onclick="copyThis(this)">Copy</button>
      </td>
    </tr>
      <td>
        <input type="hidden" value="2">
        <button type="button" class="copy" onclick="copyThis(this)">Copy</button>
      </td>
    </tr>
  </tbody>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

first, you need remove id property ("key") from your input text, because there should be no duplicate ids on a document.

Then you can change your js, taking the input ("key") element by its sibling to current clicked button.

 function myFunction(el) {
  var hidden = el.previousElementSibling;
  hidden.style.display = 'block';
  hidden.select();
  hidden.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + hidden.value);
  hidden.style.display = 'none';
}
 <table>
  <tr>
    <td class="ttd">&nbsp;</td>
    <td class="ttd">1</td>
    <td class="ttd">2</td>
    <td class="ttd">3</td>
    <td class="ttd">4</td>
    <td class="ttd">5</td>
    <td class="ttd">6</td>
    <td class="ttd">7</td>
    <td class="ttd">
      <input type="text" style="display:none;" value="12321">
      <button onclick="myFunction(this)" >Copy</button>
    </td>
  </tr>
  <tr>
    <td class="ttd">&nbsp;</td>
    <td class="ttd">1</td>
    <td class="ttd">2</td>
    <td class="ttd">3</td>
    <td class="ttd">4</td>
    <td class="ttd">5</td>
    <td class="ttd">6</td>
    <td class="ttd">7</td>
    <td class="ttd">
      <input type="text" style="display:none;" value="2222">
      <button onclick="myFunction(this)" >Copy</button>
    </td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda