简体   繁体   中英

form data not saving to chrome local storage

I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}

HTML

<form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                <label for="name">Name:</label><br />
                <input type="text" id="name" name="name"><br><br>
                <label for="email">Email:</label><br />
                <input type="email" id="email" name="email"><br><br>
                <label for="feedback">Feedback:</label><br />
                <textarea id="feedback" name="feedback"></textarea><br>
                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>
    </section>
    <script src="form.js" type="text/javascript"></script>

You have created a very pesky and hard to find bug there!

No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()"> even though it can be considered a bad practice

Spot it?

it's submit()!

Try this and submit the form

 <form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()"> <fieldset style="width: 80%; margin: auto;"> <legend>Feedback:</legend> <label for="name">Name:</label><br /> <input type="text" id="name" name="name"><br><br> <label for="email">Email:</label><br /> <input type="email" id="email" name="email"><br><br> <label for="feedback">Feedback:</label><br /> <textarea id="feedback" name="feedback"></textarea><br> <input type="submit" value="Submit" onclick="submit()"> </fieldset> </form> </section>

Surprised eh? You haven't defined getAttributeNames() anywhere yet it works? How is that you ask??

This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used onsubmit="submit()" It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method that submits it to server and once it submits obviously it won't do any localstorage business

The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly "no, use this function that I've written not the inbuilt one, please"

Here is a fixed version I just changed the name of your function

 <form action="form.html" method="get" onsubmit="submit2()"> <fieldset style="width: 80%; margin: auto;"> <legend>Feedback:</legend> <label for="name">Name:</label><br /> <input type="text" id="name" name="name"><br><br> <label for="email">Email:</label><br /> <input type="email" id="email" name="email"><br><br> <label for="feedback">Feedback:</label><br /> <textarea id="feedback" name="feedback"></textarea><br> <input type="submit" value="Submit" onclick="submit()"> </fieldset> </form> </section> <script> function submit2() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var feedback = document.getElementById("feedback").value; localStorage.setItem("name", name); localStorage.setItem("email", email); localStorage.setItem("feedback", feedback); return true; } function init() { var name = localStorage.getItem("name"); var email = localStorage.getItem("email"); var feedback = localStorage.getItem("feedback"); document.write("passed value = " + name); document.write("passed value = " + email); document.write("passed value = " + feedback); } </script>

The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!

And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.

 <form action="form.html" method="get" id="myForm"> <fieldset style="width: 80%; margin: auto;"> <legend>Feedback:</legend> <label for="name">Name:</label><br /> <input type="text" id="name" name="name"><br><br> <label for="email">Email:</label><br /> <input type="email" id="email" name="email"><br><br> <label for="feedback">Feedback:</label><br /> <textarea id="feedback" name="feedback"></textarea><br> <input type="submit" value="Submit"> </fieldset> </form> <script> var myForm = document.querySelector("form#myForm"); myForm.onsubmit = function(){ const data = {}; const dataToFetch = this.querySelectorAll("input, textarea, button, select"); for(let element of dataToFetch){ if( element && element.tagName && element.name ) data[element.name] = element.value; } let jsonData = JSON.stringify( data ); localStorage.setItem("formData", jsonData); alert("Data stored to localStorage itemName:'formData'"); return false; } </script>

I use a function for this so I can call it at any time.

// add to local storage
const addToLocalStorageObject = function (name, key, value) {
    // Get the existing data
    let existing = localStorage.getItem(name);
    // If no existing data, create an object
    // Otherwise, convert the localStorage string to an object
    existing = existing ? JSON.parse(existing) : {};
    // Add new data to localStorage object
    existing[key] = value;
    // Save back to localStorage via stringify
    localStorage.setItem(name, JSON.stringify(existing));
};

// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
    let data = localStorage.getItem(name);
    // read the localStorage item and convert it to an object
    return data ? JSON.parse(data) : null;
};

Then call addToLocalStorageObject('name', name);

And retrieveFromLocalStorageObject('name');

NB: I did not write the above functions but I have found them extremely useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM