search

Home  >  Q&A  >  body text

Delete the contents of a text area while retaining line breaks

<p>In HTML/JS, I have a script that when the enter key is pressed, it copies the text from the <code>textarea</code> and then deletes the text. The problem is, after deleting the text, the line breaks for the enter key are still there. My code is as follows: </p> <p><br /></p> <pre class="brush:js;toolbar:false;">function Send() { let lastText = document.getElementById("textInput").value; document.getElementById("sent").innerHTML = lastText; document.getElementById("textInput").value = ""; } functionKeyDetection(event) { let key = event.key; if (key == "Enter") { Send() } }</pre> <pre class="brush:html;toolbar:false;"><textarea id = "textInput" class = "textInput" rows = "1" cols = "50" placeholder = "write here" onkeydown = "KeyDetection(event)"></textarea> <p id = "sent"></p></pre> <p><br /></p> <p>I tried using null and empty string. I was hoping it would remove the newlines produced by pressing the enter key, but with no success. </p>
P粉937382230P粉937382230467 days ago476

reply all(1)I'll reply

  • P粉002546490

    P粉0025464902023-08-17 10:36:01

    If you want to prevent a newline character from being added when the Enter key is pressed, you can do this by using the event.preventDefault() method. This will effectively cancel the default behavior of the Enter key press event.

    function KeyDetection(event) {
      let key = event.key;
      if (key == "Enter") {
        event.preventDefault();
        Send();
      }
    }

    reply
    0
  • Cancelreply