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.
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 howtext()
and.val()
relate to each other:The
value
property, used by.val()
always shows the current visible value, whereastext()
's return value can be wrong..val()
always works withtextarea
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 (likeinput
) whereas.text()
fails.