1

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.

user147219
  • 355
  • 1
  • 4
  • 13

3 Answers3

2

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>
Slonski
  • 824
  • 5
  • 12
0

When you click a submit button, the default action of a form is to make a request. If there is no destination specified in your <form action=""></form>, the default location is "/" (the current page). This will reload the page.

When you say return false you are returning a false value to the caller (the form). This refuses the form to submit properly, thus preventing a reload.

Leave the return false;in there to achieve your result.

Fueled By Coffee
  • 2,467
  • 7
  • 29
  • 43
0

Why to write a lengthy JavaScript or JQuery

You can put clear button with type 'reset'. It will clear your all form field without reloading the webpage.

Eg.

 <html>
        <body>
               <form>
                        <input type="text" name="demo">
                        <button type="reset">Clear</button>
                         <button type="submit">Submit</button>
                 </form>
         </body>
  </html>
Hanumant
  • 92
  • 7