On a recent web app project that we’re building here at kc web design kent we needed to utilise HTML5 localStorage quite a lot. With the complexities of the forms we were building we also had to manipulate the DOM a lot and create whole batches of new form fields based on user input. One of the inherent problems of creating or cloning form fields using Jquery is that those new form fields aren’t accessible in the normal way. You have to use Jquery .live events to reference newly created DOM elements as click functions will not work.

Local storage issues

While building this web app at kc web design kent we wanted to use HTML5 local storage to be able to keep a reference of all data locally so that the web app could be used in off-line situations. Local storage seems like the obvious choice but we ran into problems with form fields that were created by the DOM. Local storage just would not see these new fields and no matter what we tried we couldn’t get the fields to save. There isn’t a lot of detailed information around on local storage problems like this and after a few hours on Google we came up empty. So, we decided to get our heads together at kc web design kent and build some kind of work around.

A kc web design kent fix!

After trying a few failed attempts to force local storage to see the newly created fields we decided to take a different approach and use Jquery to ‘listen’ for any changes on form fields created in the DOM and then force them to save to local storage with the correct name and value. We tried a few complicated methods but found the best way was to keep it simple. If you come across the same problem then maybe this will help. Just set up a global event to listen for all form fields and then when they change manually set the local storage values. Seems too simple to work, but it does.

$("form").on('change', function(e) { 
 var $this = e.target;
 localStorage.setItem(e.target.name, e.target.value);