Clear textarea input after enter key press

和自甴很熟 提交于 2021-02-07 12:48:49

问题


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 write return 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!