使用同一按钮复制多个文本区域

问题描述 投票:0回答:1

我编写此代码是为了使用唯一的按钮复制多个文本区域的内容,但仅复制第一个文本区域。

 var copyText = document.getElementsByClassName("form-control")[0];
 function myFunction() {

     // Get the text field

     // Select the text field
     copyText.select();
     copyText.setSelectionRange(0, 99999); // For mobile devices

     // Copy the text inside the text field
     document.execCommand("copy");

     // Alert the copied text
     alert("Copied the text: " + copyText.value);

     ///second

 } 
<textarea class="form-control" tabindex="0">something</textarea>
 <button  onclick="myFunction()">clickme</button>
<textarea class="form-control"tabindex="3" >something1</textarea>
 <button  onclick="myFunction()">clickme</button>
<textarea class="form-control" >something2</textarea>
 <button onclick="myFunction()">clickme</button>

如何解决此问题以便复制多个文本区域?

javascript html textarea
1个回答
0
投票

要使用一个按钮从文本框中复制文本,您必须遍历所有文本框并复制其内容。您可以通过以下方式调整 JavaScript 函数来实现此目的;

  1. 利用 getElementsByClassName 检索所有标记为“表单控件”的元素。
  2. 单独浏览每个文本框。复制其内容。

 function myFunction() {
        // Get all textareas with class 'form-control'
        var textAreas = document.getElementsByClassName("form-control");

        // Loop through each textarea
        for (var i = 0; i < textAreas.length; i++) {
            var copyText = textAreas[i];

            // Select the text field
            copyText.select();
            copyText.setSelectionRange(0, 99999); // For mobile devices

            // Copy the text inside the text field
            document.execCommand("copy");

            // Optional: Alert the copied text for each textarea
            alert("Copied the text: " + copyText.value);
        }
    }
<!DOCTYPE html>
<html>
<head>
    <title>Multiple Textareas</title>
</head>
<body>

<textarea class="form-control" tabindex="0">something</textarea>
<button onclick="myFunction()">Click me to copy all</button>
<textarea class="form-control" tabindex="3">something1</textarea>
<textarea class="form-control">something2</textarea>


</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.