JavaScript document.execCommandでテキストボックスの値をコピーするサンプル

環境
Google Chrome 106.0.5249.119
Windows 10 Home 64bit

構文
1.テキストボックスの値を全選択
const 変数名 = document.getElementById(セレクター名);
変数名.select()
selectメソッドを使ってテキストボックスの値を全選択にします。

2.テキストボックスの値を選択してコピー
document.execCommand(“copy");

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<input type="text" id="name" maxlength="10" value="yamadauser" />
<p><input type="button" value="テスト" onclick="funA()" /></p>
<script>
function funA() {
 //要素「name」の値を取得
const cft = document.getElementById("name");
//テキストボックスの値を全選択
cft.select();
//選択した値をコピーする
var result = document.execCommand("copy");
alert(result);
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <input type="text" id="name" maxlength="10" value="yamadauser" /> <p><input type="button" value="テスト" onclick="funA()" /></p> <script> function funA() {  //要素「name」の値を取得 const cft = document.getElementById("name"); //テキストボックスの値を全選択 cft.select(); //選択した値をコピーする var result = document.execCommand("copy"); alert(result); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>
<input type="text"  id="name" maxlength="10" value="yamadauser" />

<p><input type="button" value="テスト" onclick="funA()" /></p>

<script>
 function funA() {
 //要素「name」の値を取得
  const cft = document.getElementById("name");
  //テキストボックスの値を全選択
  cft.select();
  
  //選択した値をコピーする
  var result = document.execCommand("copy");
  alert(result); 
  }
</script>

</body>
</html>

実行結果
「テスト」ボタンを押すと、テキストボックスの値を全選択しています。
選択した値をコピーしてテキストエディターにコピーした内容を貼り付けることができます。

JavaScript

Posted by arkgame