使用 jQuery 重置多阶段表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/680241/
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
Resetting a multi-stage form with jQuery
提问by da5id
I have a form with a standard reset button coded thusly:
我有一个带有这样编码的标准重置按钮的表单:
<input type="reset" class="button standard" value="Clear" />
Trouble is, said form is of the multi-stage sort, so if a user fills out a stage & then returns later, the 'remembered' values for the various fields won't reset when the Clear button is clicked.
问题是,所述表单是多阶段排序的,因此如果用户填写了一个阶段然后稍后返回,则在单击“清除”按钮时不会重置各个字段的“记住”值。
I'm thinking that attaching a jQuery function to loop over all the fields and clear them 'manually' would do the trick. I'm already using jQuery within the form, but am only just getting up to speed & so am not sure how to go about this, other than individually referencing each field by ID, which doesn't seem very efficient.
我认为附加一个 jQuery 函数来循环所有字段并“手动”清除它们会成功。我已经在表单中使用了 jQuery,但我只是在加快速度,所以我不知道如何解决这个问题,除了通过 ID 单独引用每个字段,这似乎不是很有效。
TIA for any help.
TIA 寻求任何帮助。
回答by Paolo Bergantino
updated on March 2012.
2012 年 3 月更新。
So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.
所以,在我最初回答这个问题两年后,我回来看到它几乎变成了一团糟。我觉得是时候回到它并让我的答案真正正确了,因为它是最受好评+接受的答案。
For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.
作为记录,Titi 的答案是错误的,因为它不是原始海报所要求的 - 可以使用本机 reset() 方法重置表单是正确的,但是这个问题试图清除记住的表单如果您以这种方式重置它,将保留在表单中的值。这就是需要“手动”重置的原因。我假设大多数人最终都从 Google 搜索中找到了这个问题,并且真正在寻找 reset() 方法,但它不适用于 OP 所谈论的特定情况。
My originalanswer was this:
我原来的回答是这样的:
// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.
这可能适用于很多情况,包括 OP,但正如评论和其他答案中指出的那样,将从任何值属性中清除单选/复选框元素。
A more correctanswer (but not perfect) is:
更正确的答案(但不完美)是:
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name
Using the :text
, :radio
, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text
which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input
part of the selector, plus the cache of the form element, this should make it the best performing answer here.
使用:text
,:radio
自己等选择被认为是不好的做法,通过jQuery的,因为他们最终以评估*:text
这使得它需要比它应该更长的时间。我确实更喜欢白名单方法,并希望我在原始答案中使用过它。无论如何,通过指定input
选择器的一部分,加上表单元素的缓存,这应该使它成为这里表现最好的答案。
This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.
如果人们对 select 元素的默认设置不是一个具有空白值的选项,那么这个答案可能仍然有一些缺陷,但它肯定是通用的,因为它会得到,这需要逐案处理.
回答by Titi Wangsa bin Damhore
From http://groups.google.com/group/jquery-dev/msg/2e0b7435a864beea:
来自http://groups.google.com/group/jquery-dev/msg/2e0b7435a864beea:
$('#myform')[0].reset();
setting myinput.val('')
might not emulate "reset" 100% if you have an input like this:
myinput.val('')
如果您有这样的输入,则设置可能不会模拟“重置”100%:
<input name="percent" value="50"/>
Eg calling myinput.val('')
on an input with a default value of 50 would set it to an empty string, whereas calling myform.reset()
would reset it to its initial value of 50.
例如,调用myinput.val('')
默认值为 50 的输入会将其设置为空字符串,而调用myform.reset()
会将其重置为初始值 50。
回答by leepowers
There's a big problem with Paolo's accepted answer. Consider:
保罗接受的答案有一个大问题。考虑:
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
The .val('')
line will also clear any value
's assigned to checkboxes and radio buttons. So if (like me) you do something like this:
该.val('')
行还将清除value
分配给复选框和单选按钮的any 。所以如果(像我一样)你做这样的事情:
<input type="checkbox" name="list[]" value="one" />
<input type="checkbox" name="list[]" value="two" checked="checked" />
<input type="checkbox" name="list[]" value="three" />
Using the accepted answer will transform your inputs into:
使用接受的答案会将您的输入转换为:
<input type="checkbox" name="list[]" value="" />
<input type="checkbox" name="list[]" value="" />
<input type="checkbox" name="list[]" value="" />
Oops - I was using that value!
糟糕 - 我正在使用该值!
Here's a modified version that will keep your checkbox and radio values:
这是一个修改后的版本,它将保留您的复选框和单选值:
// Use a whitelist of fields to minimize unintended side effects.
$('INPUT:text, INPUT:password, INPUT:file, SELECT, TEXTAREA', '#myFormId').val('');
// De-select any checkboxes, radios and drop-down menus
$('INPUT:checkbox, INPUT:radio', '#myFormId').removeAttr('checked').removeAttr('selected');
回答by Francis Lewis
jQuery Plugin
jQuery 插件
I created a jQuery plugin so I can use it easily anywhere I need it:
我创建了一个 jQuery 插件,所以我可以在任何需要的地方轻松使用它:
jQuery.fn.clear = function()
{
var $form = $(this);
$form.find('input:text, input:password, input:file, textarea').val('');
$form.find('select option:selected').removeAttr('selected');
$form.find('input:checkbox, input:radio').removeAttr('checked');
return this;
};
So now I can use it by calling:
所以现在我可以通过调用来使用它:
$('#my-form').clear();
回答by Francis Lewis
document.getElementById('frm').reset()
document.getElementById('frm').reset()
回答by Cherian
Clearing forms is a bit tricky and not as simple as it looks.
清除表单有点棘手,并不像看起来那么简单。
Suggest you use the jQuery form pluginand use its clearFormor resetFormfunctionality. It takes care of most of the corner cases.
建议您使用jQuery 表单插件并使用其clearForm或resetForm功能。它处理了大多数极端情况。
回答by Ricardo Bin
I usually do:
我通常这样做:
$('#formDiv form').get(0).reset()
or
或者
$('#formId').get(0).reset()
回答by alex
Here is something to get you started
这里有一些东西可以让你开始
$('form') // match your correct form
.find('input[type!=submit], input[type!=reset]') // don't reset submit or reset
.val(''); // set their value to blank
Of course, if you have checkboxes/radio buttons, you'll need to modify this to include them as well and set .attr({'checked': false});
当然,如果你有复选框/单选按钮,你需要修改它以包含它们并设置 .attr({'checked': false});
editPaolo's answeris more concise. My answer is more wordy because I did not know about the :input
selector, nor did I think about simply removing the checked attribute.
编辑保罗的回答更简洁。我的回答比较冗长,因为我不知道:input
选择器,也没有想过简单地删除已检查的属性。
回答by dmitko
Consider using the validation plugin- it's great! And reseting form is simple:
考虑使用验证插件- 很棒!重置表单很简单:
var validator = $("#myform").validate();
validator.resetForm();
回答by Ken Le
You might find that this is actually easier solved without jQuery.
您可能会发现,如果没有 jQuery,这实际上更容易解决。
In regular JavaScript, this is as simple as:
在常规 JavaScript 中,这很简单:
document.getElementById('frmitem').reset();
I try to always remember that while we use jQuery to enhance and speed up our coding, sometimes it isn't actually faster. In those cases, it's often better to use another method.
我尽量记住,虽然我们使用 jQuery 来增强和加速我们的编码,但有时它实际上并没有更快。在这些情况下,使用另一种方法通常会更好。