简体   繁体   中英

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?

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM