-1

I have a list of elements I'd like click to copy the values inside. the elements all have the class datavalue. I'm thinking a Jquery selector with some javascript copy would help.

<div>
  <h4>IDM</h4>
  <hr />
  <dl class="dl-horizontal">
    <dt>
            FirstName
        </dt>

    <dd class="datavalue">
      John
    </dd>

    <dt>
            SecondName
        </dt>

    <dd class="datavalue">
      Baxter
    </dd>

    <dt>
            DBrith
        </dt>

    <dd class="datavalue">
      12/25/1982
    </dd>



  </dl>
</div>
Ayson Baxter
  • 510
  • 4
  • 10
  • The code you posted is returning an error. Would you be able to post a code snippet that can be run in isolation? – Adriano Feb 15 '21 at 02:38
  • Does this answer your question? https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – dale landry Feb 15 '21 at 02:54
  • No, does not. And the person who marked my question as already answered obviously didn't realize it's not a drop down list but individual elements. – Ayson Baxter Feb 15 '21 at 03:20
  • So now someone closed the question linking something that has no similarity as the answer. And here i am after figuring out the answer I can't even contribute/answer to my own question! – Ayson Baxter Feb 15 '21 at 03:51
  • https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard – Mark Schultheiss Feb 18 '21 at 22:04

2 Answers2

1

You can do something like this:

Click to copy !

$('.datavalue').on('click', function(e) {
  var text = $(e.target).text();
  copyToClipboard(text);
})

function copyToClipboard(item) {
  const x = document.createElement('TEXTAREA');
  x.value = item;
  document.body.appendChild(x);
  x.select();
  document.execCommand('copy');
  document.body.removeChild(x);
}
.datavalue:hover {
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h4>IDM</h4>
  <hr />
  <dl class="dl-horizontal">
    <dt>FirstName</dt>
    <dd class="datavalue">John</dd>

    <dt>SecondName</dt>
    <dd class="datavalue">Baxter</dd>

    <dt>DBrith</dt>
    <dd class="datavalue">12/25/1982</dd>
  </dl>
</div>
MajiD
  • 1,880
  • 1
  • 17
  • 29
0

This is what worked for me. It will copy on click any element with class "datavalue". Also will highlight the element once clicked.

<script type="text/javascript">
    $(".datavalue").css("background","#ffffff");
    $(".datavalue").click(function () {
        copyToClipboard(this);
        this.style.backgroundColor = "#ffeecc";
      //  alert('s');
    })



    function copyToClipboard(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text().trim()).select();
        document.execCommand("copy");
        $temp.remove();
    }
</script>
Ayson Baxter
  • 510
  • 4
  • 10