Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

val() vs. text() for textarea

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.

like image 382
Christophe Avatar asked Jan 13 '12 16:01

Christophe


2 Answers

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.

like image 106
Rob W Avatar answered Oct 11 '22 09:10

Rob W


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

like image 26
KJ Saxena Avatar answered Oct 11 '22 07:10

KJ Saxena