jQuery jquery如何清空输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9236332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery how to empty input field
提问by kosbou
I am in a mobile app and I use an input field in order user submit a number.
我在一个移动应用程序中,我使用一个输入字段来让用户提交一个数字。
When I go back and return to the page that input field present the latest number input displayed at the input field.
当我返回并返回输入字段的页面时,会显示输入字段中显示的最新数字输入。
Is there any way to clear the field every time the page load?
有没有办法在每次页面加载时清除该字段?
$('#shares').keyup(function(){
payment = 0;
calcTotal();
gtotal = ($('#shares').val() * 1) + payment;
gtotal = gtotal.toFixed(2);
$("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
});
回答by shaunsantacruz
You can clear the input field by using $('#shares').val('');
您可以使用清除输入字段 $('#shares').val('');
回答by osahyoun
$(document).ready(function(){
$('#shares').val('');
});
回答by Francis Lewis
Setting val('')
will empty the input field. So you would use this:
设置val('')
将清空输入字段。所以你会使用这个:
Clear the input field when the page loads:
页面加载时清除输入字段:
$(function(){
$('#shares').val('');
});
回答by Radhika
While submitting form use reset method on form. The reset() method resets the values of all elements in a form.
提交表单时,请在表单上使用重置方法。reset() 方法重置表单中所有元素的值。
$('#form-id')[0].reset();
OR
document.getElementById("form-id").reset();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
$("#submit-button").on("click", function(){
//code here
$('#form-id')[0].reset();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form-id">
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br><br>
<input id="submit-button" type="submit" value="Submit">
</form>
</body>
</html>
回答by Sablefoste
回答by chickens
To reset text, number, search, textarea inputs:
重置文本、数字、搜索、文本区域输入:
$('#shares').val('');
To reset select:
要重置选择:
$('#select-box').prop('selectedIndex',0);
To reset radio input:
重置收音机输入:
$('#radio-input').attr('checked',false);
To reset file input:
重置文件输入:
$("#file-input").val(null);
回答by chris
if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.
如果您点击“后退”按钮,它通常会粘住,您可以做的是在提交表单时清除元素,然后在进入下一页之前,但在对元素执行您需要的操作之后。
$('#shares').keyup(function(){
payment = 0;
calcTotal();
gtotal = ($('#shares').val() * 1) + payment;
gtotal = gtotal.toFixed(2);
$('#shares').val('');
$("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
});