开发者

Submit value on pressing Enter in textarea and pressing Shift+Enter should go to next line

开发者 https://www.devze.com 2023-04-03 16:46 出处:网络
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.

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.

I tried something but not able to figure out the exact keyup or keydown thing. The code I'm using at the moment is:

$("textarea").keydown(function(e){
    if (e.keyCode == 13 && !e.shiftKey)
    {
        e.preventDefault();
    }
}); 

jsFiddle

Also I want to get the \n in place when Enter+Shift key is pressed.

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.

  $.post("/incomingchat", { body:$("#chat_" + group_id).val() },
   function(data){开发者_如何学JAVA
        // do something..
    });


I've answered this before. It's a little tricky if the caret is not at the end of the textarea:

How do I detect "shift+enter" and generate a new line in Textarea?


$("textarea").keydown(function(e)
{
    if (e.keyCode == 13)
    {
        if (e.shiftKey) {
            $(this).val( $(this).val() + "\n" );
        }
        else {
            submitTheChat();
        }
    }
});


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.

$("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");        
    }    
});
0

精彩评论

暂无评论...
验证码 换一张
取 消