Skip to content Skip to sidebar Skip to footer

Prevent Input Value From Resetting On Refresh

I've noticed that in Firefox an input element maintains its value when the page is reset but not in Safari. Is there a way to maintain the values a user would have typed in JavaScr

Solution 1:

I think sessionStorage would be ideal for this since localStorage and cookies would persist the values across sessions which is probably not what you would want.


Solution 2:

<input id="persistent_text_field" value=""/>

In your JS assuming you're using jQuery

$(document).on('ready',function(){
    if(sessionStorage.getItem('last_entry')){
        $("#persistent_text_field").val(sessionStorage.getItem('last_entry'));
    }

    $("#persistent_text_field").on("keypress",function(){
        sessionStorage.setItem('last_entry',$(this).val());
    });
});

EDIT: Non jQuery Solution? Simple :)

<input id="persistent_text_field" value="" onkeypress="setStorage(this)"/>

In your JavaScript file call customReset(); in your document load event handler function.

function customReset(){
    if(sessionStorage.getItem('last_entry')){
        var element = document.getElementById("presistent_text_field");
        element.value = sessionStorage.getItem('last_entry');
    }
}

function setStorage(element){
    sessionStorage.setItem('last_entry',element.value);
}

Solution 3:

It is a browser behavior, but you can try to override it using cookies to remember entries, if you do not want to use PHP.

document.cookie = "field=value";

Solution 4:

You need to store value in cookie or in local storage.

Remember text box value using jQuery cookies


Solution 5:

Firefox itself gives an answer to this, code and all in the link:

Session Storage

The example is given in Javascript


Post a Comment for "Prevent Input Value From Resetting On Refresh"