val() vs. text() for textarea val() vs. text() for textarea jquery jquery

val() vs. text() for textarea


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 testconsole.log($(t).val('too').text('test').val());  // Prints tooconsole.log($(t).val('too').text());              // Prints nothingconsole.log($(t).text('test').val('too').val());  // Prints tooconsole.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.


.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.