简体   繁体   中英

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?

In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.

<script type="text/javascript">
    function onFormSubmit ()
    {
        document.myform.someInput.value = "";
        return true; // allow form submission to continue
    }
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>

If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).

If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.

Hope this is clear (although I doubt it, my English is quite bad sometimes)..

function testSubmit() { var x = document.forms["myForm"]["input1"]; var y = document.forms["myForm"]["input2"]; if (x.value === "") { alert('plz fill!!'); return false; } if(y.value === "") { alert('plz fill the!!'); return false; } return true; } function submitForm() { if (testSubmit()) { document.forms["myForm"].submit(); //first submit document.forms["myForm"].reset(); //and then reset the form values } }

 First Name: <input type="text" name="input1"/> <br/> Last Name: <input type="text" name="input2"/> <br/> <input type="button" value="Submit" onclick="submitForm()"/> </form>

a simple form in index.html

<form id="message-form">
      <label for="name">label</label><br />
      <input type="text" placeholder="message" name="name" /><br />
      <button>submit</button>
    </form>

index.js

const $messageForm = document.getElementById("message-form");
const $messageFormInput = $messageForm.querySelector("input");
const $messageFormButton = $messageForm.querySelector("button");

$messageForm.addEventListener("submit", e => { //listening for submit event
  e.preventDefault();

  $messageFormInput.value = "";}) //value of input will be cleared upon submit 

After successfully submitting or updating form or password you can put empty value.

CurrentPasswordcontroller.state.confirmPassword = '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM