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
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");
}
});
$("textarea").keydown(function(e)
{
if (e.keyCode == 13)
{
if (e.shiftKey) {
$(this).val( $(this).val() + "\n" );
}
else {
submitTheChat();
}
}
});
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?