Matty
Matty

Reputation: 283

Saving HTML form data to local storage

I have a form section in which people can add their email addresses.

I have a couple of problems:

(1) the page refreshes upon submitting the email address (I understand that this is unavoidable without ajax, or async solutions). It causes the second problem, however,

(2) I am seemingly unable to save these emails as an array and bring them up using JSON.parse(localStorage.getItem('EmailsStuff'))

Part of my JS/Jquery

var total = [];
                $(document).on("click", ":submit", function(e) {
                    var stuff = ($($email).val())
                    total = [JSON.stringify(stuff)];

                    localStorage.setItem('EmailsStuff', JSON.stringify(total));
            });

and html:

<form class="newsletter">

        <input type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />
        <input type="submit" value="Thanks!" class="newsletter-email" id="fast"/>
    </form>

It works if I sample:

localStorage.setItem('sample',JSON.stringify(["bob", "susan", "rafiki"]);

and consequently read it as

JSON.parse(localStorage.getItem('sample'));

Upvotes: 2

Views: 6325

Answers (2)

Calum
Calum

Reputation: 1889

It looks like the selector for your email input is wrong, try changing it to:

var stuff = $('#email').val();

And give your input an id:

<input id="email" type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />

See this Fiddle: https://jsfiddle.net/m8w1uaso/

Edit: If you want to persist all previously entered email addresses and add to this array each time the form is submitted you could do something like this:

$(document).on("click", ":submit", function(e) {
  var stuff = ($('#email').val());
    // Load emails
  var emails = JSON.parse(localStorage.getItem('EmailsStuff'));
  if (emails) {
    // If the item exists in local storage push the new email address to the array and and save
    emails.push(stuff);
    localStorage.setItem('EmailsStuff', JSON.stringify(emails));
  } else {
    // If the item doesn't exist in local storage set the item to a new array containing new email address
    localStorage.setItem('EmailsStuff', JSON.stringify([stuff]));
  }
});

$(document).on("click", "#loadEmail", function(e) {
  alert(JSON.parse(localStorage.getItem('EmailsStuff')));
});

See this Fiddle: https://jsfiddle.net/v9c6xnmh/

Upvotes: 1

afmeva
afmeva

Reputation: 879

you can prevent the form submit till you save the email array on local storage and then fire the submit.

document.getElementById("myForm").submit();

there are a few ways to prevent the form submit like

<form onsubmit="return myfunc()"... or <form onsubmit="return false"

in myFunc you must return false at the end. You can use preventDefault too.

Upvotes: 1

Related Questions