Reputation: 149
Once the submit button is pressed I want to add the li which works with this code but I also want to clear the input filed as well. Where do I add a .reset? or other method, I did a .reset() after the input and does not work. Maybe the positioning is off?
$('.sub').click(function(e){
var userInput = $('#input').val();
$('#ul').append('<li>'+userInput+'</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Enter food here</h2>
<input id = 'input'></input>
<button class ='sub'>Submit</button>
</div>
<div class = 'para'>
<h2>Shopping List</h2>
<ul id = 'ul'>
</ul>
</div>
Upvotes: 0
Views: 123
Reputation: 6597
.reset()
function works on form. You might need to wrap your HTML in the form and then do as follows -
$('.sub').click(function(e){
e.preventDefault();
var userInput = $('#input').val();
$('#ul').append('<li>'+userInput+'</li>');
$('form')[0].reset();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h2>Enter food here</h2>
<div>
<input id = 'input'></input>
<button class ='sub' type="submit">Submit</button>
</div>
<div class = 'para'>
<h2>Shopping List</h2>
<ul id = 'ul'>
</ul>
</div>
</form>
Upvotes: 1
Reputation: 978
Just set the val to empty string ("")
$('.sub').click(function(e){
var userInput = $('#input').val();
$('#ul').append('<li>'+userInput+'</li>');
$('#input').val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Enter food here</h2>
<input id = 'input'></input>
<button class ='sub'>Submit</button>
</div>
<div class = 'para'>
<h2>Shopping List</h2>
<ul id = 'ul'>
</ul>
</div>
Upvotes: 0
Reputation: 1267
Modify input
and add one line JS
to make input empty
$('.sub').click(function(e){
var userInput = $('#input').val();
$('#ul').append('<li>'+userInput+'</li>');
$('#input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Enter food here</h2>
<input id= "input" type="text" />
<button class ='sub'>Submit</button>
</div>
<div class = 'para'>
<h2>Shopping List</h2>
<ul id = 'ul'>
</ul>
</div>
Upvotes: 0
Reputation: 35
To clear a input field just set it's value to an empty string like so:
$('#input').val('');
Upvotes: 0