javascript 在返回按钮上重置表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8518671/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:41:38  来源:igfitidea点击:

Reset form on Back button

javascriptformsreset

提问by Uno Mein Ame

Trying to find an elegant solution to reset a webform (or more specifically two INPUT Type='hidden'fields) if a user goes BACK after the form is submitted.

INPUT Type='hidden'如果用户在提交表单后返回,则试图找到一种优雅的解决方案来重置网络表单(或更具体地说是两个字段)。

I understand that BACK button does not trigger an onload event.

我知道 BACK 按钮不会触发 onload 事件。

But is there any way of dealing with this?

但是有什么办法可以解决这个问题吗?

回答by dku.rajkumar

when the back button is pressed, onbeforeunloadevent is fired so you can try something like

当按下后退按钮时,onbeforeunload会触发事件,因此您可以尝试类似的操作

jQuery:

jQuery:

$('#form_id').submit(function(){
$(window).unload(function () {
$('input[type="hidden"]').val("reset_value"); 
}
});

javascript:

javascript:

<form onsubmit="call_function();">

in between script tag:

在脚本标签之间:

function call_function(){

window.onbeforeunload = function(){
var input_elems = document.getElementByTagName('input');
for(var i=0;i<input_elems.length;i++){
     if(input_elems[i].type === 'hidden'){
         input_elems[i].innerHTML = "reset_value";
     }
   }
}

回答by Flo

You could prevent the default submit from fireing, ajax-post the form, then unset the unwanted fields and change the location to a new page. Isnt really nice, but should do the trick.

您可以阻止默认提交触发,ajax 发布表单,然后取消设置不需要的字段并将位置更改为新页面。不是很好,但应该可以解决问题。

回答by Sean madden

For IE 8 or less you can reset the form : document.getElementById('formname').reset();

对于 IE 8 或更低版本,您可以重置表单: document.getElementById('formname').reset();

For IE 9, Firefox, Chrome you can reset just the fields you want by using: elementNodeHere.value = elementNodeHere.getAttribute('value');

对于 IE 9、Firefox、Chrome,您可以使用以下方法重置所需的字段: elementNodeHere.value = elementNodeHere.getAttribute('value');

Don't bother with jquery, .attr('value')returns the new value not the original

不要打扰jquery, .attr('value')返回新值而不是原始值

(getAttributein IE 7 returns the new value only and in IE 8 it can return NULL)

getAttribute在 IE 7 中只返回新值,在 IE 8 中它可以返回NULL