user1078385 user1078385 - 1 month ago 9
PHP Question

Dynamically add form elements on button press which stay after page reload

I am creating a multi page form with PHP.

I am using JavaScript to allow the user to create new text fields.

function add() {
document.getElementById('wrapper').innerHTML += '<input type="text"><br><br>';
}


As it is a multi page form the users have the option to go back to previous pages. The problem is that once the page is reloaded the extra text fields that have been added disappear. How would I go about keeping them on the page once the page is reloaded? Would I need to create a cookie to store the added form elements?

Answer

What I would do is store them in sessionStorage then bring them on page load.

function add() {
    document.getElementById('wrapper').innerHTML += '<input type="text"><br><br>';
    sessionStorage.inputBoxes = document.getElementById('wrapper').innerHTML;
}

window.load = function() {
   if (sessionStorage.inputBoxes) {
      document.getElementById('wrapper').innerHTML = sessionStorage.inputBoxes;
   }
};

I did write a plugin http://github.com/sebringj/jquery.dumbformstate that persists form state, not in terms of dynamic controls but in terms of keeping form entry state using session and local storage by the way.