Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable New Line in Textarea when Pressed ENTER

I am calling a function whenever someone press enter in the textarea. Now I want to disable new line or break when enter is pressed.

So new line should work when shift+enter is pressed. In that case, the function should not be called.

Here is jsfiddle demo: http://jsfiddle.net/bxAe2/14/

like image 994
Hassan Sardar Avatar asked Sep 13 '13 06:09

Hassan Sardar


People also ask

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How to Enter new line in textarea?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.

Does textarea support new line?

The P element renders all contiguous white spaces (including new lines) as one space. The LF character does not render to a new line or line break in HTML. The TEXTAREA renders LF as a new line inside the text area box.

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.


2 Answers

try this

$("textarea").keydown(function(e){ // Enter was pressed without shift key if (e.keyCode == 13 && !e.shiftKey) {     // prevent default behavior     e.preventDefault(); } }); 

update your fiddle to

$(".Post_Description_Text").keydown(function(e){ if (e.keyCode == 13 && !e.shiftKey) {   // prevent default behavior   e.preventDefault();   //alert("ok");   return false;   } }); 
like image 90
Scary Wombat Avatar answered Oct 22 '22 17:10

Scary Wombat


Below code is to prevent to getting resize the "textarea", avoid scroll bar inside textarea, and also prevent to get into next line when enter key is pressed.

style.css

textarea {height:200px; width:200px;overflow:hidden;resize: none;} 

index.html

<textarea></textarea> 

Script.js

$("textarea").keydown(function(e){     // Enter pressed     if (e.keyCode == 13)     {         //method to prevent from default behaviour         e.preventDefault();     } }); 
like image 35
nano dev Avatar answered Oct 22 '22 19:10

nano dev