Clear input field after submit in Jquery

Clear input field after submit using Jquery

Posted by Luke Beeno on July 30, 2022

Clear input field after submit in Jquery

Clear input field after submit using Jquery

Posted by Luke Beeno on July 30, 2022

If your using JavaScript library jquery 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 listener event 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 of input fields $("#id")

Step 4. Clear the inputs by using the val() method

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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</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>
      <button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
    </form>
    </div>
  </main>
</body>
</html>

JS

//on click event for submit button 
$( "#submitButton" ).click(function() {
    event.preventDefault(); //prevents page refresh on submit
    $("#exampleInputName").val(''); //get the input field and clear input
    $('#exampleInputEmail1').val('');
    $('#exampleInputPassword1').val('');
});