Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear textarea input after enter key press

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?

like image 450
danleyb2 Avatar asked Jul 06 '15 12:07

danleyb2


2 Answers

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.

like image 132
BrainOverflow Avatar answered Sep 30 '22 17:09

BrainOverflow


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
    }
}
like image 25
techfoobar Avatar answered Sep 30 '22 17:09

techfoobar