val() vs. text() for textarea

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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.

回答1:

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 . The following test cases illustrate how text() and .val() relate to each other:

var t = '

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.



回答2:

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



回答3:

Select by attribute name instead of id.



转载请标明出处:val() vs. text() for textarea
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!