7

I was creating some chat application using JavaScript that allows one to send a message after the enter key is pressed

window.onkeydown=function(event){ if(event.keyCode==13){ sendNew(); } } 

and in the sendNew() function;

var msg=document.getElementById('txt').value.toString().trim(); if(msg!=="") { //send message document.getElementById('txt').value = ""; } 

When you press the enter key when the textarea is onfocus the text is cleared but it seems to insert a new line character and the cursor goes to the next line in the textarea.

How can I get rid of this and have a completely empty textarea?

2 Answers 2

16

What you have to do is to cancel the default behaviour of the browser when pressing enter key (you have to prevent the browser from adding a new line).

Solution: use event.preventDefault(). Documentation: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Try out this code:

window.onkeydown=function(event){ if(event.keyCode==13){ sendNew(); if(event.preventDefault) event.preventDefault(); // This should fix it return false; // Just a workaround for old browsers } } 

Some developers forget about event.preventDefault and write return false instead. This is a bad practice, and I would suggest you the new method.

Sign up to request clarification or add additional context in comments.

1 Comment

In Chrome 53, return false actually didn't fix it for me, but event.preventDefault() did.
4

Thats because the default behavior of the enter key is to insert a new line. To prevent this from happening, return false from the keydown event handler.

window.onkeydown=function(event){ if(event.keyCode==13){ sendNew(); return false; // prevent default behavior if ENTER key } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.