New Line in Paragraph When Enter Is Pressed in Textarea

New line in paragraph when Enter is pressed in textarea

Using CSS, give #arsh (or any other elements that you want to render new lines) this attribute.

white-space: pre-wrap;

Add new line character to textarea instead of submitting form

$('textarea').keypress(function(event) {
if (event.which == 13) {
event.stopPropagation();
}
});​

JSFiddle Demo

Textarea limit enter pressed & trim the white space from new line

If I'm understanding you correctly, you can prevent users from inserting line breaks by pressing the Enter key by adding a listener. Something like this:

var textarea = document.getElementById("myTextArea");
textarea.addEventListener("keydown", function (e) {
if (e.keyCode == 13) { // keyCode 13 corresponds to the Enter key
e.preventDefault(); // prevents inserting linebreak
}
});

JSFiddle here

As for replacing multiple new lines in the string, as pointed out by @adeneo in the comments, you can use JavaScript's string.replace() function. You can add another listener on the textarea that listens on the paste event, like this:

textarea.addEventListener("paste", handler);

where handler is a function you can define that will clean the line breaks. Here's a Fiddle showing this: JSFiddle

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

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?

function getCaret(el) { 
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(), rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}

And then replacing the textarea value accordingly when Shift + Enter together , submit the form if Enter is pressed alone.

$('textarea').keyup(function (event) {
if (event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
if(event.shiftKey){
this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length);
event.stopPropagation();
} else {
this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
$('form').submit();
}
}
});

Here is a demo



Related Topics



Leave a reply



Submit