Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Store the state of a rendered form the easy way
<script>
// test for localStorage support
if(('localStorage' in window) && window['localStorage'] !== null){
var f = document.getElementById('mainform');
// test with PHP if the form was sent (the submit button has the name "sent")
<?php if(isset($_POST['sent']))){?>
// get the HTML of the form and cache it in the property "state"
localStorage.setItem('state',f.innerHTML);
// if the form hasn't been sent...
<?php }else{ ?>
// check if a state property exists and write back the HTML cache
if('state' in localStorage){
f.innerHTML = localStorage.getItem('state');
}
<?php } ?>
}
</script>
@fearphage

This comment has been minimized.

Copy link

commented Aug 25, 2010

I like the idea.

I'd put something in front of localStorage so it won't throw when it's undefined.

if (this.localStorage || 'localStorage' in this)

I think firefox requires the latter or it will freeze or crash in some versions.

@codeinfront

This comment has been minimized.

Copy link

commented Aug 27, 2010

Great idea! I recently wrote a front end app that caches the results of multiple calculations as an HTML fragment for summation purposes. Storing the inputs and results locally for future retrieval is a great feature add. I wonder if, in that scenario, we should be advising users that the results are cached from their last visit and give them an opportunity to reset.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.