我正在使用表单和重置按钮,我可以重置所有输入的值,但它根本不起作用。
当我使用Firefox控制台选项卡进行调试时,我在jQuery脚本的末尾看到了错误illegal character
。有人可以告诉我这里有什么错误吗?
<!DOCTYPE HTML>
<html lang="en-IN">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery1.7.2.js"></script>
</head>
<body>
<script type="text/javascript">
jQuery('#reset').click(function(){
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
</script>
<form id='myform'>
<input type='text' value='test' />
<select>
<option>One</option>
<option selected="true">Two</option>
</select>
<select multiple="true" size="5">
<option>One</option>
<option selected="true">Two</option>
</select>
<input type='button' id='reset' value='reset' />
</form>
</body>
</html>
答案 0 :(得分:13)
答案 1 :(得分:9)
尝试以下方法:
$(function() {
$('#reset').click(function() {
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
});
你在DOM准备好之前运行javascript。 $(function() {})
仅在DOM准备就绪时运行。在此处阅读更多内容:.ready()
答案 2 :(得分:5)
$('#form')[0].reset();` or `$('#form').get(0).reset();
$('#form').find('input, select').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
jsFiddle Working Live Demo - jQuery解决方案
document.getElementById('form').reset();
正如其中一个答案中所提到的,在大多数情况下,您不需要JavaScript来重置表单字段,它只能通过设置type="reset"
来处理按钮,例如:
<button type="reset" value="Reset">Reset</button>
答案 3 :(得分:0)
下面的JQuery将重置所有文本和下拉列表;
只需将 #YourID 替换为要重置的字段/输入的ID,对于多个输入,请复制行并在适当的地方添加ID
$(".btn-reset").click(function () {
$(this).closest('form').find("input[type=text], textarea").val("");
$('#YourID').removeAttr('selected').find('option:eq(0)').prop('selected', true);
});