开发者

functionality changes after inserting text to textarea

my questions arises from this topic. I'm stumped and have been trying it for hours. This fiddle shows a text which is inserted to a textarea when one of the options is chosen.

By typing some words in the textarea the text of the textarea will not change when I choose another option. That's ok. But when I delete the words the whole functionality is lost somehow.

If it helps you to understand what I mean and want I'll write a small 'testplan' because I'm absolutely stumped:

  1. Open the f开发者_运维问答iddle
  2. Type 'A' after 'Text' in the textarea.
  3. Select option 2 ->'TextA' stays in the textarea
  4. Now delete 'TextA'
  5. Select option1 -> as you can see the textarea stays empty though I selected option 1

How can I prevent from this behaviour? The added words to the textarea shall stay all the time. But if thereis no addition, the behavior shall not change.

Have you got an idea?


html() is the wrong way to set the contents of a textarea. Use val() instead.

The reason for this is that a textarea gets its initial value from the text contained between its start and end tags. Its current value is always stored in its value property. Changing the textarea's child nodes using innerHTML (which is what jQuery's html() method does) works initially, but once the value property has been changed (either by script or by the user editing the textarea content), the link between the textarea's child nodes and its value is broken.

Here's an updated version of your jsFiddle using val() instead of html(): http://jsfiddle.net/J4Rkt/5/

Bottom line: never use html() to get the current value of a textarea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜