Copy link to clipboard
Copied
How do I pre populate a simple html form?
Hi - I am a javascript newbie...
Q: How do I pre populate a simple html form with html5 and javascript and without using php
with php I do this:
<input id="firstname" name="firstname" value="<?php echo $firstname; ?>" type="text" />
but now I want to not use php and just use javascript to pre fill the input id="firstname"
I have this below the form...
...
document.getElementById('firstname').textContent = localStorage.getItem("firstname");
...
Q: How do I get the input form to pre fill first name?
Copy link to clipboard
Copied
I found this and it seems to work
<script> document.forms['myform'].elements['firstname'].value = localStorage.getItem("firstname"); </script>
Copy link to clipboard
Copied
As with any site, you might want to employ the help of a library. LocalStorage unfortunately isn't supported across every browsers and libraries that deal with it often fall back (if they can) to using age old cookies, automatically. They can also tell you if your code will work at all by informing you what the library detects (the ability to use local storage or cookies, etc).
An existing library that supports this and is very simple to use, including IE 7/6 polyfils, is store.js:
https://github.com/marcuswestin/store.js
e.g.
// most important, check if it even works!
if (!store.enabled) { alert('You have no local storage support here '); }
// Store 'firstname' (just shortening the form access code, season to taste)
store.set('firstname', document.getElementById('firstname').value);
// Get 'firstname'
document.getElementById('firstname').value = store.get('firstname');
// Remove 'firstname', maybe after submit
store.remove('firstname');
// clear it all
store.clear();
The examples there are pretty self explanatory and there's plenty of them.