Skip to content Skip to sidebar Skip to footer

Retain Dynamically Generated Input Fields Via Jquery After Refresh

I am using the script below to generate input fields as needed. However, upon refresh or when clicking back on the submission error page, the fields and information entered disappe

Solution 1:

If you can use HTML5 features, one way to do this is to use local storage. When creating the input fields, you save in local storage what you did.

That way, when your page is loaded, you can check what is in local storage, detect if the page was previously loaded before, and reconstruct the fields that were previously added dynamically.

Something like this:

$(document).ready(function(){
    $("#myButton").click(function(){
        var htmlAppend = '<input type="text" name="theName" />';
        $("#content").append(htmlAppend);
        //After appropriate checks that local storage is supported...localStorage.setItem("htmlAppend", htmlAppend);
    });

    var htmlAppend = localStorage.getItem("htmlAppend");
    if (htmlAppend) {
        $("#content").append(htmlAppend);
    }
});

This is of course just an example to give a direction. Other things you may want to pay attention to:

  • If several other pieces of HTML can be added through multiple events, you will have to update the local storage rather than just set it. That is: check what is already stored, and append the new content to it if any.
  • This will NOT save event handlers that you may attach to the dynamic HTML. You will have to encode it is some way in the stored value if you want to achieve that.

Solution 2:

Your problem lies with both your implementation of the server-client logic and what the actions that are erasing your elements and their data were designed to do.

When using the back button of a browser (or any shortcut for it) instead of any provided functionality within your system (such as a back button that would trigger an event that would allow you to save the data on the current page before going back), losing whatever work the user hasn't saved is the appropriate course of action (and the same applies for clicking refresh).

My recommendation to address this is to use a mix of whatever server side tools you have at your disposal to save this information whenever these events occur, (Djizeus answer is great, though you might want to take into account non HTML5 compliant browsers, unless your application is not targeted to them) and performing checks and other operations whenever the user triggers these events:

See this example for how to perform operations before the user exists the current page.

Post a Comment for "Retain Dynamically Generated Input Fields Via Jquery After Refresh"