Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - jQuery .append() not appending to textarea after text edited

Take the following page:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"/>
</head>
<body>
    <div class="hashtag">#one</div>
    <div class="hashtag">#two</div>
    <form accept-charset="UTF-8" action="/home/index" method="post">
        <textarea id="text-box"/>
        <input type="submit" value ="ok" id="go" />
    </form>

    <script type="text/javascript">
        $(document).ready(function() {

            $(".hashtag").click(function() {
                var txt = $.trim($(this).text());
                $("#text-box").append(txt);
            });

        });
    </script>
</body>
</html>

The behavior I would expect, and that I want to achieve is that when I click on one of the divs with class hashtag their content ("#one" and "#two" respectively) would be appended at the end of the text in textarea text-box.

This does happen when I click on the hash tags just after the page loads. However when I then also start editing the text in text-box manually and then go back to clicking on any of the hashtags they don't get appended on Firefox. On Chrome the most bizarre thing is happening - all the text I type manually gets replaced with the new hashtag and disappears.


I probably am doing something very wrong here, so I would appreciate if someone can point out my mistake here, and how to fix that.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

2 things.

First, <textarea/> is not a valid tag. <textarea> tags must be fully closed with a full </textarea> closing tag.

Second, $(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.

So you want to set the value, you don't want to append. Use jQuery's val() method for this.

$(document).ready(function(){
  $(".hashtag").click(function(){
    var txt = $.trim($(this).text());
    var box = $("#text-box");
    box.val(box.val() + txt);
  });
});

Working example: http://jsfiddle.net/Hhptn/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...