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>
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).
Answer: Use the reset() Method.
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('');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With