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.
This question is tagged with
~ Asked on 2012-01-13 16:58:21
The best way to set/get the value of a textarea is the
.text() internally uses the
.innerText for IE) method to get the contents of a
<textarea>. The following test cases illustrate how
.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
value property, used by
.val() always shows the current visible value, whereas
text()'s return value can be wrong.
~ Answered on 2012-01-13 17:00:54
.val() always works with
.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
~ Answered on 2014-04-10 16:50:53