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

前端 未结 3 759
一个人的身影
一个人的身影 2021-01-05 07:39

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 tr

相关标签:
3条回答
  • 2021-01-05 07:52

    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 讨论(0)
  • 2021-01-05 08:02
    $("textarea").keydown(function(e)
    {
        if (e.keyCode == 13)
        {
            if (e.shiftKey) {
                $(this).val( $(this).val() + "\n" );
            }
            else {
                submitTheChat();
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-05 08:10

    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?

    0 讨论(0)
提交回复
热议问题