How to copy text, which is in a for-each loop, to clipboard when span is clicked?

280 views Asked by At

I trying to copy data to clipboard , I want it so that whenever a user clicks on a span that contain text, that specific text it is matched up with is copied to the clipboard.

 <tbody data-bind="foreach: closedAccounts">
 <span id="a"  data-bind="text: $data.accountNo"  onclick="copyDivToClipboard()"
 data-toggle="tooltip" title="Copy to clipboard">
 </span></tbody>

javascript function

   function copyDivToClipboard() {

        var range = document.createRange();
        range.selectNode(document.getElementById("a"));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand("copy");
        console.log(range);
}

I am having trouble with copying that specific text that matches a span since the text does not have a specific id or class name because it is just printing text as it goes through the loop, so they all have the same id. So how would I specify a specific text with that span, since the spans could get pressed in any order?

2

There are 2 answers

3
cvb On

You need to use the this keyword. Pass this into your onclick function and you will be able to access the clicked element and all of its properties inside the function.

<span id="a"  data-bind="text: someText"  onclick="copyDivToClipboard(this)"
 data-toggle="tooltip" title="Copy to clipboard">
        More Text
 </span>

<script>
function copyDivToClipboard(clickedspan) {
        console.log(clickedspan)//the html element being clicked
        console.log(clickedspan.innerText)//your text here
        console.log(clickedspan.dataset.bind)//your data attribute
}
</script>
1
habib On

You can do this by passing this argument into copyDivToClipboard so then you can handle your clicked item in the function, then it's not metered weather your spans have the same id or not.

<tbody data-bind="foreach: closedAccounts">
     <span id="a"  data-bind="text: $data.accountNo"  onclick="copyDivToClipboard(this)"
       data-toggle="tooltip" title="Copy to clipboard">
     </span>
</tbody>

<script>
    function copyDivToClipboard(clickedspan) {
        const el = document.createElement('textarea');
        el.value = clickedspan.innerText;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert("Text copied to clipboard: " + clickedspan.innerText);
    }
</script>

This answer is according to your requirements specified in the question. If you want something else to achieve please edit your question.