Search code examples
jqueryappendtextareareadonly-attribute

Appended text not showing in textarea when toggling readonly or disabled attributes


I have a textarea that I would like to be either disabled or readonly. I use buttons on my site to append text to that textarea to take notes. The purpose of not allowing edits is so that no one can accidentally change any notes.

Now, if someone does need to change a note they already submitted I would like s/he to be able to edit the textarea and re-lock it for editing.

HTML:

<p><a id="append">Append</a> | <a id="lock">Lock</a> or <a id="unlock">Unlock</a></p>
<p><textarea id="notes" readonly="true" rows=10></textarea></p>

jQuery:

$("a#append").click(function() {
    $("textarea#notes").append("- This is a note.\n");
});
$("a#unlock").click(function() {
    $("textarea#notes").removeAttr("readonly");
});
$("a#lock").click(function() {
    $("textarea#notes").attr("readonly", "readonly");
});

http://jsfiddle.net/ljpaul/bakcwtaf/

Issue: when re-locking the textarea (either with readonly or disabled attribute), when I click to append another note it does not show up. Weirdly, it does show up in the HTML code, it just does not display. Does anyone have any suggestions to fix this/make it work? I feel like I have tried almost every combination of attributes and ways of setting said attributes!

Edit: a user would unlock the field to either make an edit to a note or delete a note. So when unlocked, and making any sort of edit to the contents, is when the issue occurs.


Solution

  • Looks like all it took was getting away from the .append() function.

    $("textarea#notes").val($("textarea#notes").val() + "- This is a note.\n");
    

    That does the trick and allows for editing. I think it might have something to do with append targeting the HTML structure instead of editing the actual value. Really weird.