val() vs. text() for textarea
Asked Answered
T

2

114

I am using jQuery, and wondering if I should use val() or text() (or another method) to read and update the content of a textarea.

I have tried both and I've had issues with both. When I use text() to update textarea, line breaks (\n) don't work. When I use val() to retrieve the textarea content, the text gets truncated if it's too long.

Tetartohedral answered 13/1, 2012 at 16:58 Comment(5)
what does it mean line breaks don't work?Postscript
@kaz: the text stays on the same line.Tetartohedral
And what do you mean by "text gets truncated" - in the debug output of the console? In the return value itself? Would be easier if you provided a jsfiddle...Ungracious
@Connum: in the return value. Trying jsfiddle right now...Tetartohedral
I got here by google'ing for truncated textarea text. I fixed my problem by adding a couple of \n\n to the end of the .val(). Weird but it worked.Figone
T
152

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Tali answered 13/1, 2012 at 17:0 Comment(3)
thx, trying this right now. I am currently unable to replicate the issue I had with val() and truncation. Maybe I got the wrong suspect...Tetartohedral
Thanks a bunch for the examples. Apparently that was my issue, I wrote with text() and read with val().Tetartohedral
Changing the value of a textarea using text() does NOT work anymore after manually changing anything in it (e.g. adding a character)Hick
C
15

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

Craftsman answered 10/4, 2014 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.