2

I have a copy button script:

function myFunction() {
    var table = document.getElementById('myTable');
    var copyText = table.rows[1].cells[0].innerHTML;
    copyText.select();
    document.execCommand("copy");
    alert("Copied");
}

And my table:

<table id="myTable">
{% for resp in results %}
        <tr>
            <td>{{ resp }}</td>
            <td>{{ resp.Question_id.Statement }}</td>
            <td><button onclick="myFunction()">Copy text</button></td>
        </tr>
    {% endfor %}
</table>    

I want the button to copy the text inside td {{ resp }} /td

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lloyd
  • 161
  • 3
  • 11

1 Answers1

0

function myFunction(val, event) {
  var inp = document.createElement('input');
  document.body.appendChild(inp)
  inp.value = val;
  inp.select();
  document.execCommand('copy', false);
  inp.remove();
  alert('copied');
}
<table id="myTable">
  <tr>
    <td>one</td>
    <td><button onclick="myFunction('one')">Copy text</button></td>
  </tr>

  <tr>
    <td>two</td>
    <td><button onclick="myFunction('two')">Copy text</button></td>
  </tr>

  <tr>
    <td>three</td>
    <td><button onclick="myFunction('three')">Copy text</button></td>
  </tr>

  <tr>
    <td>four</td>
    <td><button onclick="myFunction('four')">Copy text</button></td>
  </tr>

</table>

a quick solution will be passing the text (to be copied) with in the function as argu. ctrl + v to see the result.

jatinder bhola
  • 385
  • 1
  • 7
  • 23