Reset form on Back button

此生再无相见时 提交于 2019-12-06 09:22:19

问题


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.

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

But is there any way of dealing with this?


回答1:


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

jQuery:

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

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";
     }
   }
}



回答2:


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.




回答3:


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

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

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

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



来源:https://stackoverflow.com/questions/8518671/reset-form-on-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!