Saving form data to local storage and show it on refresh

前端 未结 1 1691
南笙
南笙 2020-12-30 05:33

I am making a form where users can input their data. I\'d like for this date to be saved by use of local storage. But when i refresh the page only height and weight are stil

相关标签:
1条回答
  • 2020-12-30 05:58

    You are complicating your script. Try this. Working JSFIDDLE

    If you are using jQuery once, do not mix it with pure javascript, like document.getElementById(). And do not create a height variable to store the $('#height').val(), you can use this directly. Code is more readable.

    $(document).ready(function() {
        $(window).unload(saveSettings);
        loadSettings();
    });
    
    function loadSettings() {
        $('#height').val(localStorage.height);
        $('#weight').val(localStorage.weight);
        $('#dateOfBirth').val(localStorage.dateOfBirth);
        $('input[value="' + localStorage.gender + '"]').prop('checked', true);
        $("#sportive").val(localStorage.sportive);
    }
    
    function saveSettings() {
        localStorage.height = $('#height').val();
        localStorage.weight = $('#weight').val();
        localStorage.dateOfBirth = $('#dateOfBirth').val();
        localStorage.sportive = $("#sportive").val();
        localStorage.gender = $('input[type=radio]:checked').val();
    }
    

    Update: If you are using jQuery 3, unload will throw an error. You should use this instead:

    $(window).on('unload', function(){
        saveSettings();
        loadSettings();
    });
    
    0 讨论(0)
提交回复
热议问题