-1

Here is my code, but is not working.

btn.addEventListener("click", function () {

  var get = document.getElementById('myTxtArea').value
  var res = get.split(/[ ,-]+/).join(';')
  textarea.innerText = res
  res.select();
  document.execCommand('copy');
})

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Alex 111
  • 15
  • 4

2 Answers2

0

W3: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

Another post from SO: Copying text of textarea in clipboard when button is clicked

It seems you have complicated things beyond what they need to be. Try this:

function copy() {
  let textarea = document.getElementById("textarea");
  textarea.select();
  document.execCommand("copy");
}

or

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* 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);
}
ekrenzin
  • 387
  • 2
  • 12
  • Thank you very much. Could you tell me how I can add this copied text to another textarea with the same button? – Alex 111 Jan 13 '21 at 20:37
  • For that, you don't need to copy the text to the clipboard. There are methods to get the innerText. Use that string variable to set your second text area. https://stackoverflow.com/questions/1642447/how-to-change-the-content-of-a-textarea-with-javascript something like `var text = //get the text var` `document.getElementById('secondtextarea').value = text;` – ekrenzin Jan 13 '21 at 20:47
  • Thank you very much for your attention. It turns out that I would like to modify the text of the textarea using .split (/ [, -] + /). Join (';') and when I hit the button, it would already take the modified text. But I did not succeed. And as an alternative, I will make another textarea to do this action. – Alex 111 Jan 13 '21 at 21:22
0

this works:

<textarea id="textarea">my value</textarea><br>
<button id="myButton" onclick="btnClick()">My Button</button>
//with jQuery
$(()=>{
    $("#myButton").click(()=>{
        let txtArea = $("#textarea");
        let txtVal = txtArea.val();
        // do something
        txtVal += " my added value";
        txtArea.val(txtVal);
        document.getElementById("textarea").select();
    });
});

//OR without jQuery

function btnClick() {
    let txtValue = document.getElementById("textarea").value;
    //do something
    txtValue += " add new value";
    document.getElementById("textarea").value = txtValue;
    document.getElementById("textarea").select();
}
Denny
  • 1
  • 1