I need a way to clear all the fields within a form when a user uses the browser back button. Right now, the browser remembers all the last values and displays them when you go back.
More clarification on why I need this I've a disabled input field whose value is auto-generated using an algorithm to make it unique within a certain group of data. Once I've submitted the form and data is entered into the database, user should not be able to use the same value again to submit the same form. Hence I've disabled the input field in the first place. But if the user uses the browser back button, the browser remembers the last value and the same value is retained in the input field. Hence the user can submit the form with the same value again.
What I don't understand is what exactly happens when you press the browser back button. It seem like the entire page is retrieved from cache without ever contacting the server if the page size is within the browser cache limit. How do I ensure that the page is loaded from the server regardless of browser setting when you press the browser back button?
bind("click", function() { $("input[type=text], textarea"). val(""); }); This will clear all fields on the page, not just the ones from the form.
You can easily reset all form values using the HTML button using <input type=”reset”> attribute. Clicking the reset button restores the form to its original state (the default value) before the user started entering values into the fields, selecting radio buttons, checkboxes, etc. There could be many scenarios.
Another way without JavaScript is to use <form autocomplete="off">
to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"
> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow
and pagehide
events:
window.addEventListener("pageshow", () => { // update hidden input field });
See more details for Gecko and WebKit implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With