LoginSignup
0
0

More than 5 years have passed since last update.

JavaScriptでクリップボードにelementのvalueをコピーする

Posted at

やること

  • ボタンをクリックしたときにelementのvalueをコピーする
  • jQueryは使わない

コード

textareaを用意して、文字を入れて、全選択して、コピーする

JavaScript
  function copyToClipboard(element) {
    var text = document.createElement("textarea");
    text.classList.add('hidden'); 
    text.value = element.value;
    document.body.appendChild(text);
    text.select();
    document.execCommand("copy");
    text.remove();
    alert('Copied!!');
  }
CSS
.hidden {
    display: none;
}
HTML
<!-- idを引数にしたら、elementが変数に入ってる状態になるんだね、知らなかった -->
<button name="button" type="submit" onclick="copyToClipboard(target)">コピーする</button>
<input type="hidden" id="target" value="aaaaaaaaaa">
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0