Search code examples
javascriptjqueryhtmlhtml5-historyhtml-input

How to include user input in the html string of a some parent DOM element?


I want to store the content of a div container in windows history, by running the following line:

window.history.pushState($('#myDivId').html(), "title", 'some url');

I would later use this info when user presses the back button.


Problem:

User has a form to fill, with one input. User types his name (say John) and clicks on submit. The onSubmit function is triggered and here I get the html content of parent div and store it in history object. The problem is, user input (John) in this example, is not captured.

The following screenshot shows the output of my script below:

enter image description here

Code Snippet

function onSubmit() {
   var str = $('#myDivId').html();
   alert("this goes to windows history: " + str);
   // window.history.pushState($('#myDivId').html(), "title", 'some url');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="onSubmit()">
   <div id="myDivId">
      First name: <input id="firstNameId" type="text" name="FirstName" value=""><br>
      <input type="submit" value="submit">
   </div>
</form>

How can include user input in the str before pushing it in the history?

Update:

This is a simplified example, in the real scenario I have several input fields in the container. So I am looking for a way to capture all the input values through the container.


Solution

  • The value attribute represents the default value of the field, not the current value.

    There is no HTML attribute which reflects that.

    If you want to store it, then you need to store it explicitly.

    I'd approach this by using serializeArray() (and converting it to JSON to store in the history), and then looping over it to restore the data to the form.