user1854438 user1854438 - 3 months ago 24
HTML Question

How do I clear a textarea with jquery

This question has been answered, but for future reference here is a full example.

You can click the add button and clear button as many times as you want and it will work. But once you type something in the text box, then the clear and and add buttons do not work.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){

$("#add").click(function(){

$("#box").append("Test, ")
});

$("#clean").click(function(){
$("#box").text("")
});

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

<button id="add">ADD</button><br/>
<textarea rows="10" cols="50" id="box"></textarea><br/>
<button id="clean">Clear Box</button>

</body>
</html>

Answer

When dealing with elements that expect input from the user you should use jQuery's val function:

$(function() {
  $('#b1').click(function() {
      $("#textarea").val($("#textarea").val() + "This is a test");
  });
  $('#c1').click(function() {
    $("#textarea").val("")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea><br />
<button id="b1">Append</button> <button id="c1">Clear</button> 

The append function changes the DOM, and this is not what you are trying to do here (This is what breaks the default behavior of the textarea element).

Comments