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.