问题
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?
回答1:
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 writereturn false
instead. This is a bad practice, and I would suggest you the new method.
回答2:
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
}
}
来源:https://stackoverflow.com/questions/31245808/clear-textarea-input-after-enter-key-press