Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset input field? jQuery

I've read several posts, including this, and this, but I can't seem to get the input field to clear out after submitting. What is the most basic / elementary way to do this?

Currently I have this:

$(document).ready(function(){
    $('form[name=checkListForm]').on('submit', function() {
          // prevent the form from submitting
          event.preventDefault();
          var toAdd = $(this).find('input[name=checkListItem]').val();
          $('.list').append("<div class='item'>" + toAdd + "</div>")
          $('input[name=checkListItem').reset();
        });
});

My HTML is:

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">  
    <link rel="stylesheet" href="stylesheet.css">     
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
  </head>
  <body>
    <h2>To Do</h2>
    <form name="checkListForm">
      <input type="text" name="checkListItem" />
      <button type="submit" id="button">Add!</button>
    </form>
    <br/>
    <div class="list"></div>
  </body>
</html>
like image 428
TheRealFakeNews Avatar asked Feb 18 '16 20:02

TheRealFakeNews


People also ask

How do I reset a JQ form?

JQuery doesn't have a reset() method, but native JavaScript does. So, we convert the jQuery element to a JavaScript object. JavaScript reset(): The reset() method resets the values of all elements in a form (same as clicking the Reset button).

How do you clear form data after submit in jQuery?

Answer: Use the reset() Method.


1 Answers

Instead of resetting, just set a blank value to the input field using this bit of code:

$('input[name=checkListItem').val('');

In order to reset all inputs in a particular form you could also use the following code (using the :input selector):

$('form :input').val('');
like image 81
stark Avatar answered Sep 28 '22 02:09

stark