Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I stop ENTER from adding a newline to my textarea?

While working on a chatting application, I’ve encountered the following problem:
For the user to write his messages, I have implemented a textarea through HTML, and when said user presses enter, it does indeed send the message, but it also adds a newline to said textarea. Can I add something to the end of my EventListener in order to remove the newline? Thanks. (Edit: I need to be able to send the messages with ENTER, but not have the effect of it on my textarea text). Here’s my EventListener:

document.addEventListener('keydown', e => {
    if (e.key == "Enter"){
        send();
        //solution goes here...
    }
});

Setting the value of the textarea to "" doing TA.value = ""; didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Event.preventDefault()

document.querySelector('textarea').addEventListener('keydown', e => {
  if (e.key === 'Enter') {
    console.log('send')
    e.preventDefault()
  }
})
<textarea></textarea>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading