用jQuery重置多阶段表单

我有一个标准的重置button,因此编码forms:

<input type="reset" class="button standard" value="Clear" /> 

麻烦的是,表单是多阶段sorting的,所以如果用户填写了一个阶段然后返回,那么当点击清除button时,各个字段的“记住”值将不会被重置。

我想附加一个jQuery函数来遍历所有的领域,并清除他们“手动”会做的伎俩。 我已经在表单中使用了jQuery,但是我们只是想加快速度,所以我不知道如何去做,除了单独引用每个字段的ID,这似乎不是很有效。

TIA的任何帮助。

2012年3月更新。

所以,在我回答这个问题两年之后,我回过头来看到它已经变成了一个大乱子。 我觉得是时候回到这个问题上来,让我的答案真正正确,因为这是最有价值的+被接受的。

为了logging,Titi的答案是错误的,因为它不是原始海报所要求的 – 可以使用本地reset()方法重置表单是正确的,但是这个问题试图清除记住的表单如果以这种方式重新设置,将保留在表单中的值。 这就是为什么需要“手动”重置的原因。 我猜想大多数人都是通过Googlesearch结束了这个问题,并且真正在寻找reset()方法,但是对于OP所谈论的特定情况,它并不起作用。

原来的答案是这样的:

 // not correct, use answer below $(':input','#myform') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); 

这可能适用于许多情况,包括OP,但正如在评论和其他答案中指出的,将清除任何值属性的无线电/checkbox元素。

正确的答案(但不完美)是:

 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 

使用:text:radio等select器本身被jQuery认为是不好的做法,因为它们最终会对*:text进行求值,这会使得它花费比预期更长的时间。 我更喜欢白名单的方法,并希望我用我原来的答案。 无论如何,通过指定select器的input部分,再加上表单元素的caching,这应该使其成为performance最佳的答案。

如果人们对select元素的默认值不是一个空值的选项,这个答案可能仍然有一些缺陷,但是它肯定是一般的,因为它将会得到,这将需要在个案的基础上处理。

来自http://groups.google.com/group/jquery-dev/msg/2e0b7435a864beea

 $('#myform')[0].reset(); 

设置myinput.val('')可能不会模仿“重置”100%,如果你有这样的input:

 <input name="percent" value="50"/> 

例如,对默认值为50的input调用myinput.val('')会将其设置为空string,而调用myform.reset()会将其重置为初始值50。

保罗接受的答案有一个很大的问题。 考虑:

 $(':input','#myform') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); 

.val('')行也将清除分配给checkbox和单选button的任何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转换为:

 <input type="checkbox" name="list[]" value="" /> <input type="checkbox" name="list[]" value="" /> <input type="checkbox" name="list[]" value="" /> 

糟糕 – 我正在使用这个值!

这是一个修改后的版本,将保持您的checkbox和电台值:

 // 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'); 

清算表格有点棘手,并不像看起来那么简单。

build议您使用jQuery表单插件并使用其clearFormresetFormfunction。 它照顾了大部分的angular落案件。

jQuery插件

我创build了一个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; }; 

所以现在我可以通过调用它来使用它:

 $('#my-form').clear(); 

我通常做:

 $('#formDiv form').get(0).reset() 

要么

 $('#formId').get(0).reset() 

的document.getElementById( 'FRM')。复位()

考虑使用validation插件 – 这太棒了! 而重置表单很简单:

 var validator = $("#myform").validate(); validator.resetForm(); 

这是让你开始的东西

 $('form') // match your correct form .find('input[type!=submit], input[type!=reset]') // don't reset submit or reset .val(''); // set their value to blank 

当然,如果你有checkbox/单选button,你需要修改它以包含它们,并设置.attr({'checked': false});

编辑 保罗的答案更简洁。 我的答案更罗嗦,因为我不知道:inputselect器,也没有考虑简单地删除选中的属性。

我觉得这个效果很好。

 $(":input").not(":button, :submit, :reset, :hidden").each( function() { this.value = this.defaultValue; }); 

基本上没有提供的解决scheme让我感到高兴。 正如less数人指出的那样,他们将表格清空而不是重新设定。

然而,有一些JavaScript的帮助:

  • 文本字段的defaultValue
  • 默认检查checkbox和单选button
  • defaultSelectedselect选项

这些存储页面加载时字段的值。

写一个jQuery插件现在是微不足道的(对于不耐烦…这是一个演示http://jsfiddle.net/kritzikratzi/N8fEF/1/

插件代码

 (function( $ ){ $.fn.resetValue = function() { return this.each(function() { var $this = $(this); var node = this.nodeName.toLowerCase(); var type = $this.attr( "type" ); if( node == "input" && ( type == "text" || type == "password" ) ){ this.value = this.defaultValue; } else if( node == "input" && ( type == "radio" || type == "checkbox" ) ){ this.checked = this.defaultChecked; } else if( node == "input" && ( type == "button" || type == "submit" || type="reset" ) ){ // we really don't care } else if( node == "select" ){ this.selectedIndex = $this.find( "option" ).filter( function(){ return this.defaultSelected == true; } ).index(); } else if( node == "textarea" ){ this.value = this.defaultValue; } // not good... unknown element, guess around else if( this.hasOwnProperty( "defaultValue" ) ){ this.value = this.defaultValue; } else{ // panic! must be some html5 crazyness } }); } } )(jQuery); 

用法

 // reset a bunch of fields $( "#input1, #input2, #select1" ).resetValue(); // reset a group of radio buttons $( "input[name=myRadioGroup]" ).resetValue(); // reset all fields in a certain container $( "#someContainer :input" ).resetValue(); // reset all fields $( ":input" ).resetValue(); // note that resetting all fields is better with the javascript-builtin command: $( "#myForm" ).get(0).reset(); 

一些笔记…

  • 我还没有看到新的html5表单元素,有些可能需要特殊的处理,但同样的想法应该工作。
  • 元素需要直接引用。 即$( "#container" ).resetValue()将不起作用。 总是使用$( "#container :input" )
  • 如上所述,这里是一个演示: http : //jsfiddle.net/kritzikratzi/N8fEF/1/

你可能会发现,这实际上更容易解决没有jQuery。

在普通的JavaScript中,这很简单:

 document.getElementById('frmitem').reset(); 

我试着总是记住,虽然我们使用jQuery来加强和加速我们的编码,但有时实际上并不快。 在这些情况下,使用其他方法通常会更好。

我做了弗朗西斯·刘易斯的一个很好的解决scheme的细微变化 他的解决scheme不做的是将下拉select设置为空白。 (我认为当大多数人想要“清除”时,他们可能希望使所有的值都为空)。这个用.find('select').prop("selectedIndex", -1)

 $.fn.clear = function() { $(this).find('input') .filter(':text, :password, :file').val('') .end() .filter(':checkbox, :radio') .removeAttr('checked') .end() .end() .find('textarea').val('') .end() .find('select').prop("selectedIndex", -1) .find('option:selected').removeAttr('selected') ; return this; }; 

我通常添加一个隐藏的重置button的forms。 当需要时只需:$('#reset')。click();

修改$(document).ready()情况下得票最多的答案:

 $('button[type="reset"]').click(function(e) { $form = $(this.form); $form.find('input:text, input:password, input:file, select, textarea').val(''); $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected'); e.preventDefault(); }); 

只需使用如下所示的jQuery Trigger event

 $('form').trigger("reset"); 

这将重置checkbox,单选button,文本框等…本质上,它将您的窗体变成默认状态。 只需将# #ID, Class, element放在jQueryselect器中。

这工作对我来说,pyrotex答案didn'重置select领域,把他的,在这里'我的编辑:

 // Use a whitelist of fields to minimize unintended side effects. $(':text, :password, :file', '#myFormId').val(''); // De-select any checkboxes, radios and drop-down menus $(':input,select option', '#myFormId').removeAttr('checked').removeAttr('selected'); //this is for selecting the first entry of the select $('select option:first', '#myFormId').attr('selected',true); 

我正在使用Paolo Bergantino解决scheme,这个解决scheme非常棒,但是几乎没有任何调整…特别是使用表单名称而不是id。

例如:

 function jqResetForm(form){ $(':input','form[name='+form+']') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); } 

现在当我想用它可以做

 <span class="button" onclick="jqResetForm('formName')">Reset</span> 

正如你所看到的,这与任何forms的工作,因为我使用CSS风格来创buildbutton页面不会刷新时单击。 再一次感谢Paolo的意见。 唯一的问题是如果我有默认值的forms。

我使用下面的解决scheme,它为我工作(混合传统的JavaScript与jQuery)

 $("#myformId").submit(function() { comand="window.document."+$(this).attr('name')+".reset()"; setTimeout("eval(comando)",4000); }) 

我只是PHP中的一个中介,有点懒得钻研像JQuery这样的新语言,但是下面不是简单而优雅的解决scheme吗?

 <input name="Submit1" type="submit" value="Get free quote" /> <input name="submitreset" type="submit" value="Reset" /> 

看不到为什么没有两个提交button,只是为了不同的目的。 然后简单地:

 if ($_POST['submitreset']=="Reset") { $_source = "--Choose language from--"; $_target = "--Choose language to--"; } 

您只需将您的值重新定义为默认值即可。

我对Paolo Bergantino的原始答案做了一些改进

 function resetFormInputs(context) { jQuery(':input', context) .removeAttr('checked') .removeAttr('selected') .not(':button, :submit, :reset, :hidden') .each(function(){ jQuery(this).val(jQuery(this).prop('defautValue')); }); } 

这样,我可以将任何上下文元素传递给函数。 我可以重置整个表单或只重置一组字段,例如:

 resetFormInputs('#form-id'); // entire form resetFormInputs('.personal-info'); // only the personal info field set 

另外,input的默认值被保留。

我在一个相当大的表单(50+字段)上使用的一个方法是只用AJAX重新加载表单,基本上callback到服务器,并返回字段的默认值。 这比使用JS获取每个字段然后将其设置为默认值要容易得多。 它也允许我保持默认值在一个地方 – 服务器的代码。 在这个网站,也有一些不同的默认值,这取决于帐户的设置,因此我不必担心将这些发送到JS。 我唯一需要处理的小问题是一些build议在AJAX调用之后需要初始化的字段,但不是什么大问题。

所有这些答案都很好,但最简单的方法就是使用假复位,即使用链接和重置button。

只需添加一些CSS来隐藏真正的重置button。

 input[type=reset] { visibility:hidden; height:0; padding:0;} 

然后在你的链接添加如下

 <a href="javascript:{}" onclick="reset.click()">Reset form</a> <input type="reset" name="reset" id="reset" /><!--This input button is hidden--> 

希望这可以帮助! 一个。

 <script type="text/javascript"> $("#edit_name").val('default value'); $("#edit_url").val('default value'); $("#edit_priority").val('default value'); $("#edit_description").val('default value'); $("#edit_icon_url option:selected").removeAttr("selected"); </script> 

在这里刷新checkbox并select:

 $('#frm').find('input:text, input:password, input:file, textarea').val(''); $('#frm').find('input:radio, input:checkbox').attr("checked",false).checkboxradio("refresh"); $('#frm').find('select').val('').selectmenu('refresh'); 

我遇到同样的问题,保罗的职位帮助我,但我需要调整一件事。 我的表单与id advancedindexsearch只包含input字段,并从会话中获取值。 出于某种原因,以下方面对我不起作用:

 $("#advancedindexsearch").find("input:text").val(""); 

如果我在此之后发出警报,我看到正确删除的值,但之后又被replace。 我仍然不知道如何或为什么,但是下面这一行确实为我做了这个诀窍:

 $("#advancedindexsearch").find("input:text").attr("value",""); 

保罗的答案没有考虑dateselect器,添加此:

 $form.find('input[type="date"]').val(''); 

这里是我的解决scheme,它也适用于新的html5inputtypes:

 /** * removes all value attributes from input/textarea/select-fields the element with the given css-selector * @param {string} ele css-selector of the element | #form_5 */ function clear_form_elements(ele) { $(ele).find(':input').each(function() { switch (this.type) { case 'checkbox': case 'radio': this.checked = false; default: $(this).val(''); break; } }); } 
 $(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);