1

I'm trying to copy string variable to clipboard.

I could find a lot of examples that copy the values from < input > or < p > tags, But my problem in case I make a changes on variable then I want to copy it such as this example

var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");
Ali H
  • 903
  • 14
  • 36
  • Then apply the changes/value to the `input` before executing the copy to the clipboard script... – NewToJS Jan 21 '18 at 19:38

2 Answers2

3

var getNum1 = function() {
  return 1;
};

var getNum2 = function() {
  return 2;
};

var num1 = getNum1();
var num2 = getNum2();
var result = ((num1 * num2) / 3) - 1;

var executeCopy = function() {
  var copyhelper = document.createElement("input");
  copyhelper.className = 'copyhelper'
  document.body.appendChild(copyhelper);
  copyhelper.value = result;
  copyhelper.select();
  document.execCommand("copy");
  document.body.removeChild(copyhelper);
};

document.getElementById('mybutton').addEventListener('click', function() {
  executeCopy();

  alert("your results has been copied");
});
.copyhelper {
  position: absolute;
}
<button id='mybutton'>Copy to clipboard</button>

Hope it helps!

Ele
  • 33,468
  • 7
  • 37
  • 75
0

I got the solution

var dummy = document.createElement("input");
//dummy.style.display = 'none'
document.body.appendChild(dummy);
//$(dummy).css('display','none');
dummy.setAttribute("id", "dummy_id");
//dummy.setAttribute('value', document.URL + '; ' + document.title)
dummy.setAttribute('value', textX) //TEXTX is the value of variable
//document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
Ali H
  • 903
  • 14
  • 36