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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With