Search code examples
javascriptselectphpmailer

html Select not saving data after history.back() is callled


I am building a form using phpmailer, witch consists of 3 steps: the form itself, information confirmation page and mail sent message page. When the user is on the information confirmation page, he is able to go back and correct the information that was written, by busing onclick="history.back();". Everything is working fine, all fields remain written as the user did, with exception of a select button for years that is using the following code:

<select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>

<script>
var start = 1900;
    var end = new Date().getFullYear();
    var options = "<option disabled selected value>年</option>";
    for(var year = start ; year <=end; year++){
        options += "<option>"+ year + "年" + "</option>";
    }
    document.getElementById("f_year").innerHTML = options;
</script>

When its clicked to correct the information, the data from this select element is not saved at all. What should I do?


Solution

  • Check the following out. This is a Minimal, Complete and Verifiable Example of your problem scenario.

    As you can see, there are two SELECT elements, that one is hard-coded and the other is dynamically generated (the same script that you have provided).

    <html>
        <body>
            <select>
                <option value="Val1">V1</option>
                <option value="Val2">V2</option>
                <option value="Val3">V3</option>
                <option value="Val4">V4</option>
                <option value="Val5">V5</option>
            </select>
            <select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>
            <script>
                var start = 1900;
                var end = new Date().getFullYear();
                var options = "<option disabled selected value>年</option>";
                for(var year = start ; year <=end; year++){
                    options += "<option>"+ year + "年" + "</option>";
                }
                document.getElementById("f_year").innerHTML = options;
            </script>
            <button onclick="window.location='confirm.php'">Proceed</button>
        </body>     
    </html>
    

    When you try running this, you'd see that the hard-coded one stays intact, while the dynamically generated one resets, when you navigate back to the same, from the confirm page.

    What happens is, when you navigate back, the scripts on the page will execute from the beginning, changing the values, hence the dynamically generated inputs will be reset. Only the static content could be kept intact. To keep the dynamic stuff intact, you will need some extra work.

    This question looks similar to your problem scenario, which is suggesting something for those extra work you need to do to preserve the dynamic content.