我正在寻找一个jQuery函数,将清除后提交表单的所有字段的表单。
我没有任何HTML代码显示,我需要一些通用的东西。
你能帮上忙吗?
谢谢!
发布于 2013-02-27 01:38:48
类似于$("#formId").reset()
的内容不会清除默认设置为""
以外的其他内容的表单项目。发生这种情况的一种方式是以前的表单提交:表单提交后,reset()
会将表单值“重置”为以前提交的表单,而这些值很可能不是""
。
要清除页面上的所有表单,一种选择是调用如下所示的函数,将其简单地作为clearForms()
执行
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
如果要重置特定表单,请按如下所示修改该函数,并将其调用为clearForm($("#formId"))
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
当我最初来到这个页面时,我需要一个解决方案,该解决方案考虑到正在更改的表单默认值,并且仍然能够清除所有输入项。
请注意,这不会清除placeholder
文本。
发布于 2011-07-12 00:52:25
将val
设置为"“
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
您也可以尝试如下所示:
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
发布于 2011-07-12 00:51:13
<form id="form" method="post" action="action.php">
<input type="text" class="removeLater" name="name" /> Username<br/>
<input type="text" class="removeLater" name="pass" /> Password<br/>
<input type="text" class="removeLater" name="pass2" /> Password again<br/>
</form>
<script>
$(function(){
$("form").submit(function(e){
//do anything you want
//& remove values
$(".removeLater").val('');
}
});
</script>
https://stackoverflow.com/questions/6653556
复制相似问题