2

Hello Guys I want to copy input value yeah on button click But nothing work. Please Help!!

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

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

<button class="btn btn-primary btn-block" onclick="copyToClipboard('#myvalue')">Copy myvalue</button>
4
  • 2
    Possible duplicate of How do I copy to the clipboard in JavaScript? Commented Dec 4, 2017 at 12:13
  • @anddy but i want to copy input value :( how to do this ?? Commented Dec 4, 2017 at 12:15
  • In clipboard or in another element? Commented Dec 4, 2017 at 12:16
  • means input value yeah i want to copy this :) Commented Dec 4, 2017 at 12:17

3 Answers 3

11

function copyToClipboard() {
    var textBox = document.getElementById("myvalue");
    textBox.select();
    document.execCommand("copy");
}
<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

     <button class="btn btn-primary btn-block" onclick="copyToClipboard()">Copy myvalue</button>

Sign up to request clarification or add additional context in comments.

Comments

1

document.execCommand() is now obsolete, the alternative is Clipboard API, via navigator.clipboard. Per MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API):

function copyToClipboard() {
  var textBox = document.getElementById("myvalue");
  console.log(textBox.value)
  navigator.clipboard.writeText(textBox.value);
}
<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH YEAH" readonly  />
<button class="btn btn-primary btn-block" onclick="copyToClipboard()">Copy myvalue</button>

Comments

0

Code if you want to copy input text to ClipBoard.

//HTML
<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />
<button class="btn btn-primary btn-block" onclick="copyToClipboard();">Copy myvalue</button>


//SCRIPT For ClipBoard Copy
 <Script>
    function copyToClipboard() {
        var textBox = document.getElementById("myvalue");
        textBox.select();
        document.execCommand("copy");
    }
</Script>



//For local storage variable copy
<Script>
    function copyToStorage() {
        var textBox = document.getElementById("myvalue");
        if(typeof(Storage) !== "undefined") {

            var textBox_value=textBox.value;
            localStorage.setItem("textBox_value", textBox_value);
         } else {
               alert("Sorry your browser does not support this script");
           }
    }
</Script>

   // Also there one to use an element like hidden to store the value for same page life.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.