javascripthtmlresetposting

How to reset just texbox, not the entire page?


I am trying to create a posting/commenting system. It does most of what I want. Now, I want to have just the textbox reset, not the whole page. Skeleton code is preset by CodePen. (More explanation with the code sample)

HTML:

<form id="frmPost" name="write">
    <div class="textbox">
        <input class="postwriter" name="post" type="text" placeholder="What's on your mind?" id="txtPost">
        <button id="btnPost" onclick= "return write_below(this); resetText();" value="submit" >Post</button>
    </div>
</form>
<div class="posts" id="postDisplay">
    <p class="para"><span id='display'></span></p>
</div>

JS:

function resetText() {
    document.getElementById('txtPost').value="";
    //return false;
}
function write_below(form){
    var input = document.forms.write.post.value;
    //document.getElementById('display').innerHTML += input + "<br/>" + "<br/>";
    document.getElementById('display').innerHTML += "<p>" + Math.floor(Math.random()*20) + ": " + input + "</p>" + "<br/>";
    return false;
}

Like this, the post is kept but the textbox is reset. If I get rid of/comment out the second return false; the entire page resets.


Solution

  • All you have to do is call resetText() from write_below()

    function resetText() {
        document.getElementById('txtPost').value="";
    }
    function write_below(form){
      var input = document.forms.write.post.value;   
      document.getElementById('display').innerHTML += "<p>" + Math.floor(Math.random()*20) + ": " + input + "</p>" + "<br/>";
      resetText();
      return false;
    }
    <form id="frmPost" name="write">
      <div class="textbox">
        <input class="postwriter" name="post" type="text" placeholder="What's on your mind?" id="txtPost">
        <button id="btnPost" onclick= "return write_below(this);" value="submit" >Post</button>
      </div>
    </form>
    <div class="posts" id="postDisplay">
      <p class="para"><span id='display'></span></p>
    </div>