4

I am developing a keyboard plugin. Which requires that if the user clicks on the enter key, then it must add the newline in that textarea.

I have tried adding other characters, such as a b c etc. But in case of newline I know a newline in js is added using

\n

But, when I try to append this to the textarea it just adds that to the textarea's text. While I want it to start a newline. How can I get the new line?

Here is the code that runs with each click:

$('#vboard li').click(function () {
  CurVal = $(LastFocused).val();
    $(LastFocused).val(CurVal + $(this).attr('id'));
    $(LastFocused).focus();
});

The above code executes and appends the current button's value to the element. When I click on enter key, it gives me output as value + '\n' for example:

If the value was afzaal, then after the click it would change to afzaal\n instead of starting a new line.

How would I get the newline in textarea?

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103

3 Answers3

4

You need to add a new new dynamicaly, right? Give this a try and see if this is what you wanted.

$('textarea').html($('textarea').val()+'
Something');

I'm setting html of textarea instead of its val


It seems even this works fine

$('textarea').val($('textarea').val()+'\nSomething');
Milindu Sanoj Kumarage
  • 2,714
  • 2
  • 31
  • 54
2

this one should work with vanila Javascript:

var newMessage="please add me to the new line";

const textarea = document.getElementById('messages');

element.value += "\n"+ newMessage;

Amir
  • 105
  • 5
1

try somthing like

<textarea cols='60' rows='8'>This is my first line.&#13;&#10;This is my second line </textarea>

using &#10; and &#13; will let you on new line without displaying in textarea

Anand Jha
  • 10,404
  • 6
  • 25
  • 28
  • Same result brother, it adds `\n` to the value. – Afzaal Ahmad Zeeshan Jan 22 '14 at 16:34
  • That's great in the HTML, and you found it [here](http://stackoverflow.com/questions/8627902/new-line-in-text-area), using entities, but setting the elements value with javascript entities won't work. – adeneo Jan 22 '14 at 16:34
  • I like it , this works best for embedding a line break directly in text area. – Edgy Sep 20 '20 at 21:00