Alcides Alcides - 1 month ago 10
Javascript Question

How to append content to a textarea after modifying manually its content

I have an input and textarea, and I'm capturing the enter on the input and I'm appending that line to the textarea, this works fine, but when I make some edition directly on the textarea like delete or insert some text, the programatic insert doesn't work anymore. How can I fix this?

I've tested this in Chrome 53, Firefox 49.0.2 and Opera 40, so it seems that's not a browser problem. Here a code that I've tried to work with:



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<input type="text" id="entry" name="entry"><br>
<textarea id="result" rows="10"></textarea>

<script type="text/javascript">
$("#entry").on("keyup", function(e){
if (e.keyCode == 13){
$("#result").append( $("#entry").val()+"\n");
$("#entry").val("");
}
});
</script>




Answer

One way of textarea doesn't to lost the reference of value is save it, and then concat the existing value of the new entry, something like this..

$("#entry").on("keyup", function(e){
  if (e.keyCode == 13){
    var text = $("#result").val();
    $("#result").val( text +  $("#entry").val()+"\n");    
    $("#entry").val("");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<input type="text" id="entry" name="entry"><br>
<textarea id="result" rows="10"></textarea>

Comments