Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea : elem.val() vs elem.text() [duplicate]

This is very weird. Apparently, I can use both .val() and .text() to manipulate textarea text.

But after I use .val to change the text, I cannot use .text anymore. The converse is not true.

This is leading to some funky bugs. The reason is because a plugin i am using might be using .val to manipulate the text.

Can anyone explain how this works? Thanks!

like image 667
meow Avatar asked Oct 19 '10 00:10

meow


3 Answers

You have to use val(), or (better) the value property of the textarea. text() works initially because the initial value of the textarea is determined by the text node (if any) it contains. You can even initially change the nodeValue or data property of this text node and it will update the textarea's value. However, as soon as either the user has altered the value of the textarea or script has altered the value property of the textarea, the text node is out of the picture and is no longer bound to the textarea's value in any way.

like image 93
Tim Down Avatar answered Oct 07 '22 11:10

Tim Down


The .val() function gets the "value" attribute of the <textarea> element, while .text() gets the contents of the text nodes (node type 3) in the element. I'd say that if setting .text() works at all, it's not a good idea, as it's essentially fooling around with the basic building blocks of matter. It could cause a bug, or a browser crash, or a devastating explosion.

Use .val().

edit.text() works up to the point at which a user interacts with the <textarea> element, or JavaScript code sets the "value" property. After that point, the DOM content of the element becomes irrelevant. You can still get it, but it won't reflect the actual state of the element.

like image 23
Pointy Avatar answered Oct 07 '22 11:10

Pointy


Sounds strange, but at a lower level, .val() is what I'm expecting to work since .value is the way to access the content of form-elements. Why .text() is working in some cases beats me

like image 40
Onkelborg Avatar answered Oct 07 '22 09:10

Onkelborg