How do I clear a textarea with jquery

笑着哭i 提交于 2020-06-26 13:43:20

问题


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>

回答1:


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).



来源:https://stackoverflow.com/questions/38984133/how-do-i-clear-a-textarea-with-jquery

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