简体   繁体   中英

How do I get rid of form input value cache in JavaScript?

This is my code in JavaScript:

function myfunction() {
    var increment = $("#increment").val();
    $("#increment").val(parseInt($("#increment").val()) + 1);
}

and HTML:

<input id="increment" value="0" type="hidden">

The idea is when I click on my button the myfunction is called and increment my input type hidden with one. It works. If press the F5 button the value from the input type hidden remain with the last increment number.

If I press Ctrl + F5 the value from my input will be set to 0 . Why? How do I build my code in order to set my input to 0 when I simply refresh my page with F5 ?

You could simply set the value to 0 on page load:

$(function() {
    $("#increment").val('0');
});

EDIT: Samuels answer above solves this specific issue brilliantly, that is, by resetting back to 0. My answer below is the generic way to prevent browsers from persisting FORM data when you refresh. To do that, the browser cache needs to be disabled.

You need to disable client caching in the browser.

The only way to do that on the client side is by using meta tags:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Just before the function do the following:

$('#increment').val(''); // This should always make the input clear of any value when the page loads
function myfunction(){
    var increment = $("#increment").val();
    $("#increment").val(parseInt($("#increment").val()) + 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM