javascript 在 textarea 中按 Enter 提交值并按 Shift+Enter 应转到下一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7344972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit value on pressing Enter in textarea and pressing Shift+Enter should go to next line
提问by Mohit Jain
I want to have a chat box (textarea) where if user press Enter then it should submit the chat, and if user press Shift+Enter then it should enter in a new line.
我想要一个聊天框(textarea),如果用户按 Enter 则它应该提交聊天,如果用户按 Shift+Enter 则它应该输入一个新行。
I tried something but not able to figure out the exact keyup or keydown thing. The code I'm using at the moment is:
我尝试了一些东西,但无法弄清楚确切的 keyup 或 keydown 事情。我目前使用的代码是:
$("textarea").keydown(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
}
});
Also I want to get the \n
in place when Enter+Shift key is pressed.
我也想\n
在按下 Enter+Shift 键时就位。
EDIT
编辑
Issue with my code is:-
我的代码问题是:-
When i am check the content on client using using alert then it shows the next line. But when i am posting it my rails back end. Then its just a simple string. No new line thing is there.
当我使用警报检查客户端上的内容时,它会显示下一行。但是当我发布它时,我的导轨后端。那么它只是一个简单的字符串。没有新的线路。
This is how i am sending chats to rails server.
这就是我将聊天发送到 rails 服务器的方式。
$.post("/incomingchat", { body:$("#chat_" + group_id).val() },
function(data){
// do something..
});
采纳答案by Tim Down
I've answered this before. It's a little tricky if the caret is not at the end of the textarea:
我以前回答过这个。如果插入符号不在 textarea 的末尾,则有点棘手:
How do I detect "shift+enter" and generate a new line in Textarea?
回答by AndreyKo
$("textarea").keydown(function(e)
{
if (e.keyCode == 13)
{
if (e.shiftKey) {
$(this).val( $(this).val() + "\n" );
}
else {
submitTheChat();
}
}
});
回答by pedrodg
Consider using the keypress event instead. If you run the code in jsfiddle, you'll see that a new line is not added when you press enter.
考虑改用按键事件。如果您在 jsfiddle 中运行代码,您会看到按回车键时没有添加新行。
$("textarea").keypress(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
//now call the code to submit your form
alert("just enter was pressed");
return;
}
if (e.keyCode == 13 && e.shiftKey)
{
//this is the shift+enter right now it does go to a new line
alert("shift+enter was pressed");
}
});