Currently, if the person presses enter inside the text area, the form will submit.
Good, I want that.
But when they type shift + enter, I want the textarea to move to the next line: n
How can I do that in JQuery
or plain JavaScript as simple as possible?
Advertisement
Answer
Better use simpler solution:
Tim’s solution below is better I suggest using that: https://stackoverflow.com/a/6015906/4031815
My solution
I think you can do something like this..
EDIT : Changed the code to work irrespective of the caret postion
First part of the code is to get the caret position.
Ref: How to get the caret column (not pixels) position in a textarea, in characters, from the start?
JavaScript
x
17
17
1
function getCaret(el) {
2
if (el.selectionStart) {
3
return el.selectionStart;
4
} else if (document.selection) {
5
el.focus();
6
var r = document.selection.createRange();
7
if (r == null) {
8
return 0;
9
}
10
var re = el.createTextRange(), rc = re.duplicate();
11
re.moveToBookmark(r.getBookmark());
12
rc.setEndPoint('EndToStart', re);
13
return rc.text.length;
14
}
15
return 0;
16
}
17
And then replacing the textarea value accordingly when Shift + Enter together , submit the form if Enter is pressed alone.
JavaScript
1
14
14
1
$('textarea').keyup(function (event) {
2
if (event.keyCode == 13) {
3
var content = this.value;
4
var caret = getCaret(this);
5
if(event.shiftKey){
6
this.value = content.substring(0, caret - 1) + "n" + content.substring(caret, content.length);
7
event.stopPropagation();
8
} else {
9
this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
10
$('form').submit();
11
}
12
}
13
});
14
Here is a demo