[javascript] How to reload current page without losing any form data?

Can I reload current page without losing any form data? I used..

window.location = window.location.href;

and

window.location.reload(true);

But these two things can't get earlier form datas for me. What is wrong ? When refresh browser manually, it is fine (I don't lose any form data). Please guide me how to figure it out.

Here is my full code...

<div class="form-actions">
        <form>
            <table cellpadding = "5" cellspacing ="10">
                <tr class="control-group">
                    <td style="width: 100px;">
                        <div>Name:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input type="text" id="inputName" placeholder="Name" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Email:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input class="span3" placeholder="[email protected]" id= "inputEmail" type="email" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Phone:&nbsp;</div>
                    </td>
                    <td>
                        <input type="text" id="inputPhone" placeholder="phone number">
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Subject:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input type="text" id="inputSubject" placeholder="Subject" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td colspan ="2">
                        <div>
                            <div>Detail:&nbsp;</div>
                            <div class="controls">
                                <textarea id="inputDetail"></textarea>
                            </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                    <div>
                        <label style="font-weight: bold;" class="checkbox"> <input id="confirmCheck" value="" type="checkbox">
                                I Agree to the Personal information handling policy
                        </label>
                    </div>
                    <div id = "alert_placeholder"></div>
                        <div class="acceptment">
                            [Personal information handling policy]<br> <br>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div align="center">
                            <button id="btnConfirm" class="btn btn-primary">Confirm</button>
                            <input type="reset" style="width: 65px; height: 27px;" id="btnReset" class="btn">
                        </div>
                    </td>
                </tr>
            </table>
        </form>
    </div>

And at my JS file..

function bind() {
$('#btnConfirm').click(function(e) {
    if ($('#confirmCheck').is(":checked")) {
        getConfirmationForSendFAQ();
    }
    else {
        e.preventDefault();
        showalert("You should accept \"Personal Information Policy\" !", "alert-error");
    }
});};function getConfirmationForSendFAQ() {
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var phone = $('#inputPhone').val();
    var subject = $('#inputSubject').val();
    var detail = $('#inputDetail').val();

    $('.form-actions').empty();
    html = [];
    html.push("<table cellpadding ='8' class = 'submitInfo'");
    html.push("<tr>");
    html.push("<td class = 'title'>Name:</div>");
    html.push("<td class = 'value'>"+ name +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td class = 'title'>Email Address:</div>");
    html.push("<td class = 'value'>"+ email +"</td>");
    html.push("</tr>");

    if (phone.trim().length > 0) {
        html.push("<tr>");
        html.push("<td class = 'title'>Phone No:</div>");
        html.push("<td class = 'value'>"+ phone +"</td>");
        html.push("</tr>");
    }

    html.push("<tr>");
    html.push("<td class = 'title'>Subject:</div>");
    html.push("<td class = 'value'>"+ subject +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td class = 'title'>Detail Info:</div>");
    html.push("<td class = 'value'>"+ detail +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td colspan='2'><div align = 'center'>");
    html.push("<button id='btnSend' class='btn btn-primary' style='width: 65px;'>Send</button>");
    html.push("<button id='btnReturn' class='btn btn-inverse' style='width: 65px; height: 27px; margin-left: 5px;'>Return</button>");
    html.push("</div></td></tr>");

    html.push("</table>");
    $('.form-actions').append(html.join(''));
    $('#btnReturn').click(function(e) {
        // HERE I WANT TO KNOW HOW TO DO.....
    });
    $('#btnSend').click(function(e) {
        alert("Doom");
    });}

This question is related to javascript jquery html jquery-ui

The answer is


You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.


You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.

let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)

The optional second parameter of each FormPersistence function defines whether to use local storage (false) or session storage (true). In your case, session storage is likely more appropriate.

The form data by default will be cleared from storage upon submission, unless you pass false as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.


This answer was extremely helpful to me, and saves the trouble of going through each field manually:

Using jQuery to store the state of a complicated form


As some answers mention, localStorage is a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.


I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.

<script>
    // Run on page load
    window.onload = function() {

        // If sessionStorage is storing default values (ex. name), exit the function and do not restore data
        if (sessionStorage.getItem('name') == "name") {
            return;
        }

        // If values are not blank, restore them to the fields
        var name = sessionStorage.getItem('name');
        if (name !== null) $('#inputName').val(name);

        var email = sessionStorage.getItem('email');
        if (email !== null) $('#inputEmail').val(email);

        var subject= sessionStorage.getItem('subject');
        if (subject!== null) $('#inputSubject').val(subject);

        var message= sessionStorage.getItem('message');
        if (message!== null) $('#inputMessage').val(message);
    }

    // Before refreshing the page, save the form data to sessionStorage
    window.onbeforeunload = function() {
        sessionStorage.setItem("name", $('#inputName').val());
        sessionStorage.setItem("email", $('#inputEmail').val());
        sessionStorage.setItem("subject", $('#inputSubject').val());
        sessionStorage.setItem("message", $('#inputMessage').val());
    }
</script>

I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.


Agree with HTML5 LocaStorage. This is example code


Find this on GitHub. Specially created for it.

https://gist.github.com/zaus/4717416


Register an event listener for keyup event:

document.getElementById("input").addEventListener("keyup", function(e){
  var someVarName = input.value;
  sessionStorage.setItem("someVarKey", someVarName);
  input.value = sessionStorage.getItem("someVarKey");
});

window.location.reload() // without passing true as argument

works for me.


You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete