• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

How do I pre populate a simple html form with html5 and javascript?

Contributor ,
Sep 13, 2015 Sep 13, 2015

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?

Views

2.4K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Contributor ,
Sep 13, 2015 Sep 13, 2015

Copy link to clipboard

Copied

I found this and it seems to work

     <script> document.forms['myform'].elements['firstname'].value = localStorage.getItem("firstname"); </script>

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 17, 2015 Sep 17, 2015

Copy link to clipboard

Copied

LATEST

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines