natureminded natureminded - 1 year ago 117
HTML Question

How can I remove the empty line break at the bottom of my textarea after appending text using jQuery?

This is could be a very basic question, as what I'm wishing for here doesn't seem that crazy -- I looked throughly for some existing answer or better solution to this already, so I apologize in advance if this is any form of duplicate!

My question regards append()ing data to an existing textarea element:



<textarea id='chat'></textarea>

My JS/jQuery:

//note: 'chatMsg' data is provided back from the server
$('#chat').append(': '+chatMsg.message+'&#10;');
$('#chat').scrollTop($('#chat')[0].scrollHeight); // focuses on bottom of textarea

My desired output: New lines append to the textarea, each new message as a new line. No extra lines at the bottom of the texarea.

What I'm experiencing: Indeed, new lines append to the textarea, each as a new line (due to the use of the
HTML carriage return). However, because of this new line character being at the end of my
string, a blank line is added beneath my last message (see: for a screenshot). Adding the carriage return to the front of the string would fix the extra line break at the bottom, but would create a line break at the very top when the first message is sent.

I understand another way to approach this is by grabbing the
, adding my new data as a new line, such as:

var oldChat = $('#chat').val();
var newChat = oldChat + '&#10;' + + ': ' + chatMsg.message;

However, when I try this approach, hoping to add the new message as a new line beneath the
, the HTMl carriage characters do not display and instead show as text (see: I also tried using the
character but this actually killed my javascript
(not shown) and my chat broke.

Is there some better way to add new lines to my chat while not ending up with an extra white space at the bottom?

Note: Another possible solution I thought of was to try and somehow use regex to grab the last line and remove it, but I thought I would ask here if there was a simpler way to do this, or if I'm being too picky wanting my textarea to append text nice and clean (no extra line breaks).

Answer Source

You could have the newLine BEFORE instead of after, and in order to make sure there's no new line above the very first line, check if the textarea is empty.

so (pesudo code here but hopefully you get the idea)

string = chatmessage
// Prepend newline to string if the textarea already contains content
if textarea.value.length !== 0
  string = '&#10;' + string

textarea.value = string
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download