一旦按下提交按钮,我想添加与此代码一起使用的li,但我也想清除输入字段。我在哪里添加.reset?或其他方法,我在输入后做了一个.reset(),但是不起作用。也许位置不对?
$('.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>
答案 0 :(得分:1)
.reset()
函数适用于表单。您可能需要将HTML包装在表单中,然后执行以下操作-
$('.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>
答案 1 :(得分:0)
要清除输入字段,只需将其值设置为空字符串,如下所示:
$('#input').val('');
答案 2 :(得分:0)
修改input
并添加一行JS
以使输入为空
$('.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>
答案 3 :(得分:0)
只需将val设置为空字符串(“”)
$('.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>