Monday, November 21, 2011

jQuery's .append() function doesn't work as expected, so use .val() for object string appends


$(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.
    var txt = $.trim($(this).text());
    var box = $("#text-box");
    box.val(box.val() + txt);
Working example:

No comments:

Post a Comment