3 回答
TA贡献1862条经验 获得超7个赞
// not correct, use answer below$(':input','#myform').not(':button, :submit, :reset, :hidden').val('').removeAttr('checke在我最初回答这个问题
的两年后,我回来发现这个问题已经变成了一团乱。我觉得是时候回过头来,让我的答案真正正确,因为它是最令人兴奋的+接受。为了记录在案,Titi的回答
是错误的,因为这不是最初的海报所要求的-使用本机Reset()方法重置表单是正确的,但是这个问题是试图清除表单中的记住值,如果您以这种方式重置的话,
这些值将保留在表单中。这就是为什么需要“手动”重置。我想大多数人最终都会在Google搜索中问到这个问题,并且正在真正地寻找Reset()方法,但对于OP
所讨论的具体情况,它不起作用。我的原版答案是:// not correct, use answer below$(':input','#myform').not(':button, :submit, :reset, :hidden
').val('').removeAttr('checked').removeAttr('selected');这可能适用于许多情况,包括OP,但正如注释和其他答案中所指出的,它将清除任何值属性中的
收音机/复选框元素。更多对,是这样答案(但不完美)是:function resetForm($form) { $form.find('input:text, input:password, input:file, selec
t, textarea').val(''); $form.find('input:radio, input:checkbox') .removeAttr('checked').removeAttr('selected');}// to call, use
:resetForm($('#myform')); // by id, recommendedresetForm($('form[name=myName]')); // by name使用:text, :radio等,选择器本身被jQuery认为是
错误的实践,因为它们最终评估为*:text这使得它花费的时间比它应该花的时间要长得多。我确实更喜欢白名单的方法,并希望我在我最初的答案中使用它。
无论如何,通过指定input选择器的一部分,加上Form元素的缓存,这将使它成为这里性能最好的答案。如果人们对SELECT元素的默认设置不是一个具有空白
值的选项,那么这个答案可能仍然有一些缺陷,但是它肯定是一个通用的选项,而且它将需要逐个案例地处理。d').removeAttr('selected');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, recommendedresetForm($('form[name=myName]')); // by name:text, :radio*:textinput
TA贡献2036条经验 获得超8个赞
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');.val('')value
<input type="checkbox" name="list[]" value="one" /><input type="checkbox" name="list[]" value="two" checked="checked" /> <input type="checkbox" name="list[]" value="three" />
<input type="checkbox" name="list[]" value="" /><input type="checkbox" name="list[]" value="" /><input type="checkbox" name="list[]" value="" />
// 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');- 3 回答
- 0 关注
- 529 浏览
相关问题推荐
添加回答
举报
