Clear input field after submit in JavaScript

Clear input field after submit in JavaScript

Posted by Ervin Adams on July 30, 2022

Clear input field after submit in JavaScript

Clear input field after submit in JavaScript

Posted by Ervin Adams on July 30, 2022

If your using JavaScript to submit a form, you might need to clear the input fields after submit.

Here is how you clear the input fields:

Step 1. Add onClick attribute with onSubmit() function to submit button 

Step 2. On click of the submit button prevent form from submitting the default way using event.preventDefault()

Step 3. Get the specified elements using document.getElementById()

Step 4. Clear the inputs by using the attrubute value

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 clear form input</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
    <form>
      <div class="mb-3">
        <label for="exampleInputName" class="form-label">Name</label>
        <input type="text" class="form-control" id="exampleInputName">
      </div>
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">Email address</label>
        <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
      </div>
      <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">Password</label>
        <input type="password" class="form-control" id="exampleInputPassword1">
      </div>
      <!--The JavaScript function "onSubmit" is added to the submit button using attribute "onClick" -->
      <button type="submit" class="btn btn-primary" id="submitButton" onClick='onSubmit()'>Submit</button>
    </form>
    </div>
  </main>
</body>
</html>

JS

function onSubmit(){
    event.preventDefault(); //prevents page refresh on submit

    const name = document.getElementById('exampleInputName'); //get the input field
    const email = document.getElementById('exampleInputEmail1');
    const password = document.getElementById('exampleInputPassword1');


    name.value = ''; //clear the input field
    email.value = '';
    password.value = '';
}