Home > OS >  Clear search after form submit
Clear search after form submit

Time:07-17

I would like the search bar to be cleared after the user presses the search button. Is there a quick workaround that is not invasive?

<form method="POST" id="Submit">
              <div >
                <div >
                  <input id="search" name="input" placeholder="Paste here" type="text" required oninvalid="onInvalid(event)" />
                </div>
            
                <div >
                  <button id="button"  onclick="searchIt()" value="press" type="submit">
                      SEARCH
                  </button>
                </div>
              </div>
              <p  id="errorMessage"></p>
            </form>

CodePudding user response:

Bind the submit event to the <form>:

document.forms.Submit.onsubmit = e => /* ... */

then call the .reset() method on the <form> via e.target, also wrap it in a setTimeout():

/* ... */ setTimeout(() => e.target.reset(), 0)

I have the <form> sending data to a live test server and an <iframe> to display the response so you can see that after a search the <input> is cleared.

<form action='https://httpbin.org/post' method="POST" id="Submit" target='response'>
  <div >
    <div >
      <input id="search" name="input" placeholder="Paste here" type="text" required oninvalid="onInvalid(event)" />
    </div>

    <div >
      <button name='btn'  value="press" type="submit">SEARCH</button>
    </div>
  </div>
  <p  id="errorMessage"></p>
</form>
<iframe name='response'></iframe>
<script>
document.forms.Submit.onsubmit = e => setTimeout(() => e.target.reset(), 0);
</script>

CodePudding user response:

You can delete the text on input search.

function searchIt(){
  document.getElementById('search').value="";
}
<form method="POST" id="Submit">
  <div >
    <div >
      <input id="search" name="input" placeholder="Paste here" type="text" required oninvalid="onInvalid(event)" />
    </div>

    <div >
      <button id="button"  onclick="searchIt()" value="press" type="submit">
          SEARCH
      </button>
    </div>
  </div>
  <p  id="errorMessage"></p>
</form>

CodePudding user response:

function searchIt(e){

e.preventDefault();
/* do what you want
   submit form
*/

document.getElementById('Submit').reset()
}
<form method="POST" id="Submit">
  <div >
    <div >
      <input id="search" name="input" placeholder="Paste here" type="text" required oninvalid="onInvalid(event)" />
    </div>

    <div >
      <button id="button"  onclick="searchIt(event)" value="press" type="submit">
                      SEARCH
                  </button>
    </div>
  </div>
  <p  id="errorMessage"></p>
</form>

  • Related