user7455781
user7455781

Reputation:

How to copy input's value with clipboard.js

I don't know how to copy the value to clipboard from the input without using ID!

Here is JS:

  new Clipboard(".form__copy-btn", {
    target: function (trigger) {
      return $(trigger).closest(".form__field-wrapper").find("input");
    }
  });

Here is codepen

Upvotes: 2

Views: 984

Answers (4)

user7455781
user7455781

Reputation:

Also, I found another answer, here it is:

  new Clipboard(".form__copy-btn", {
    target: function (trigger) {
      return $(trigger).closest(".form__field-wrapper").find("input").get(0);
    }
  });

Upvotes: 0

Kashyap
Kashyap

Reputation: 391

I have checked your codepen. I have made below changes and copy is working

  1. Remove clipboard js plugin code from js and add itin setting as external resource resource in js section (external resource cdn link: https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js)

  2. I have made below change in your code

    /** I have used text method for copy and it is working **/
    var clipboard = new Clipboard(".form__copy-btn", {
    text: function(trigger) {
            // console.log($(trigger).closest(".form__field-wrapper").find("input").val());
      return $(trigger).closest(".form__field-wrapper").find("input").val();
    }
    });
    

Upvotes: 0

Miro
Miro

Reputation: 8650

Two things are happening here:

  1. jQuery doesn't work withing the clipboard return function. I passed it using var j = $;

  2. You are trying to return a jQuery element and clipboard.js only takes a native JS element. Instead of using target: use text: - that way you can pass the exact text string instead of the element.

This worked for me:

var j = $;

_document.ready(function () {

new Clipboard(".form__copy-btn", {
    text: function(trigger) {
        return j(trigger).closest(".form__field-wrapper").find("input").val();
    }
  });

...

Codepen

Upvotes: 2

kmg
kmg

Reputation: 519

You can use document.execCommand('copy') to copy the value to clipboard from the input. See link to check details and browser compatibility.

Upvotes: 0

Related Questions