Home > Software design >  How to repopulate form input value after Page Submit/Reload
How to repopulate form input value after Page Submit/Reload

Time:07-20

I am trying to re-populate the saved form inputs after a submit/page reload. The problem I'm running into is the input field populates the saved value (or just any string) but then resets almost immediately. What am I missing? Thanks

Flask (Server):

@app.route("/code", methods=["GET", "POST"])
def code():
    value = request.form["field1"]
    return render_template(
    "code.html",
    saved_inputs = value
)

Html:

    <form action="{{ url_for('code') }}" method="post" id="form">
        <label for="field1">Test Input 1 </label>
        <input type"text" name="field1" id="field1">
        <button type="submit"  id="btnSubmit">Submit</button>
    </form>

JS:

    <script>
        $("#form").on('submit', function(event){
            event.preventDefault();

            // convert form to JSON
            var formData = new FormData(document.getElementById('form'));
            var formJSON = {};

            for (var entry of formData.entries())
            {
                formJSON[entry[0]] = entry[1];
            }
            result = JSON.stringify(formJSON)
            console.log("results is: " result);


            // set JSON to local Storage
            sessionStorage.setItem('formObject', result);
    
            // submit form
            document.getElementById("form").submit();
            
            // decode sessionstorage object
            var decodedObj = JSON.parse(sessionStorage.getItem('formObject'));
            console.log("sessionStorage object: " decodedObj);
            // alert("value is: " decodedObj["field1"]);
            // alert("jinja value is: " "{{ saved_inputs }}");

            // retrieve localStorage and populate input
            // this is not working as expected
            document.getElementById("field1").value =  "WHY ISN'T THIS SAVING??";
            // document.getElementById("field1").value =  '{{ saved_inputs }}';
        })

    </script>

CodePudding user response:

You can try storing the values in local storage & then retrieve them whenever the page is reloaded. You have used Session Storage. See.

CodePudding user response:

I think the issue you are facing is that you are not checking when the page load--only when the form is submitted. To load the form on page load we can use sessionStorage to check if the record exists and then load the object to the form.

$(function() {
  const formObj = sessionStorage.getItem('formObject');
  // Load object
  if (formObj != null) {
    console.log("Previous form session exists")
    let decodedObj = JSON.parse(formObj);
    console.log("sessionStorage object: "   decodedObj);
    console.log("value is: "   decodedObj["field1"]);

    // retrieve sessionStorage and populate input
    console.log("Loading previous session");
    document.getElementById("field1").value = decodedObj["field1"];
  }
});

Proof of concept fiddle

  • Related