Prevent input value from resetting on refresh

2019-07-04 01:57发布

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 JavaScript (no PHP).

I've tried Googling this fairly extensively but every result seems to find this behavior undesirable.

Edit: Not sure what I am doing wrong, this is what I tried:

<input id="myInput" type="text">
<script>
    var myInput = document.getElementById("myInput");

    if (sessionStorage.getItem("autosave"))
        myInput.value = sessionStorage.getItem("autosave");

    myInput.addEventListener("change", function() {
        sessionStorage.setItem("autosave", myInput.value);
    });
</script>

Edit (again): Got it working, thank you:

<input id="myInput" type="text">
<script>
    var myInput = document.getElementById("myInput");

    window.onload = function() {
        if (sessionStorage.getItem("autosave"))
            myInput.value = sessionStorage.getItem("autosave");
    }

    myInput.addEventListener("keyup", function() {
        sessionStorage.setItem("autosave", myInput.value);
    });
</script>

4条回答
聊天终结者
2楼-- · 2019-07-04 02:37

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.

查看更多
你好瞎i
3楼-- · 2019-07-04 02:43

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";
查看更多
趁早两清
4楼-- · 2019-07-04 02:46

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

Remember text box value using jQuery cookies

查看更多
太酷不给撩
5楼-- · 2019-07-04 02:47
<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);
}
查看更多
登录 后发表回答