Append text to text area with jquery issue

橙三吉。 提交于 2019-12-08 00:27:38

问题


Im trying to make some buttons append text to a textarea with jquery, and I have it working, but only if I dont type anything into the textarea itself.

Code:

<textarea name="comments" id="comments" rows="20" style="margin-left: 0px; margin-right: 0px; width: 968px;"></textarea>
<div>
  <button>+petname</button>
  <button>+lastvisit</button>
  <button>+nextvisit</button>
</div>
<script>
$( "button" ).click(function() {
  var text = $( this ).text();
  $('#comments').append(text); 
});
</script>

This code is working, but the minute I type something else into that text area, the buttons no longer work??? WHY!!?? I just cant figure it out. Much thanks. Jason


回答1:


Instead of doing append set val using its function argument syntax, do this way:

$('#comments').val(function(_, val){
    return val + text; 
}); 

Demo




回答2:


change

$('#comments').append(text);

to

$('#comments').val( $('#comments').val() + " " + text );


来源:https://stackoverflow.com/questions/20602241/append-text-to-text-area-with-jquery-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!