简体   繁体   中英

How do I make this 'profile' form localy store the data? Javascript

I am a beginner in Javascript, so please bear with me. I have this assignment:

  1. Create a class called 'Profile' that has three methods: (a) setProfile(n, a, e, t); which takes four parameters and assign the values to local variables i. Name, ii. Age, iii. Email, iv. Telephone number, and calls the saveProfile() method, (b) getProfile() which reads the local stored data if it exists and display the profile values in the respective fields on the profile page. (c) saveProfile() stores the profile data to Local Storage.

  2. Update function validateForm() such that: a. Name cannot be less than 3 characters. b. Age should be between 12 and 95. c. Email is a valid @ntnu.no address. d. Number cannot be more than 7 digits. e. Make sure none of the fields are empty.

  3. Create an object “myProfile” of type 'Profile' class in a function called 'UpdateProfile'. Add following functionality in this function: a. Validate the fields. b. setProfile() only when the fields are validated.

This function “UpdateProfile” is called when a user presses the Update button (1.c).

  1. Create a function called 'displayProfile()' that calls the getProfile() method. Invoke 'displayProfile()' on page load so that whenever profile.html page is launched, if the data is locally stored, the form is populated with the stored data.

What I don't understand is how to "read the local stored data and display the profile values in the respective fields on the profile page". The methods should work together some how shouldn't it?

Here's my code:

<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
</head>
<body onload="displayProfile()">

<h1> Profile </h1>

Your Name
<form name="Login" method="post" action="#" onsubmit="return validateForm()">

<input type="text" name="fName" id="FN"> <br>

Age <br>
<input type="text" name="ageField" id="age"> <br>

Email <br>
<input type="text" name="email" id="e"><br>

Number <br>
<input type="text" name="number" id="num">


<input onclick="saveProfile(); UpdateProfile();" type="submit" name="sub" value="Update">

</form>


<script type="text/javascript">

    class Profile {

        setProfile(n, a, e, t) {


            this.name = n;
            this.age = a;
            this.email = e;
            this.telephoneNumber = t;

            this.saveProfile();
        }

        getProfile() {
            document.getElementById("FN").value = name;
            document.getElementById("age").value = age;
            document.getElementById("e").value = email;
            document.getElementById("num").value = telephoneNumber;
        }

        saveProfile() {
            let storeName = document.getElementById('FN').value;
            localStorage.setItem('name', storeName);
            let storeAge = document.getElementById('age').value;
            alert(storeAge);
            localStorage.setItem('age', storeAge);
            let storeEmail = document.getElementById('e').value;
            localStorage.setItem('email', storeEmail);
            let storeNum = document.getElementById('num').value;
            localStorage.setItem('number', storeNum);
        }

    }

    function validateForm() {

        var x = document.forms['Login']['fName'].value;
        if(x==null || x=="")
        {
            alert("Please enter your name");
            document.getElementById('FN').focus();
            //return false;
        } else if (x.length < 3) {
            alert("Password must be over 3 characters");
            document.getElementById("FN").focus();
            //return false
        } 

        a = document.forms['Login']['ageField'].value;
        if(a==null || a=="")
        {
            alert("age can not be empty");
            document.getElementById('age').focus();
            //return false;
        }
        else if(parseInt(a)<12 || parseInt(a) > 95)
        {
            alert("age should be between 12 and 95");
            document.getElementById('age').focus();
            //return false;
        }


//https://www.udemy.com/blog/javascript-validation-2/?utm_source=adwords&utm_medium=udemyads&utm_campaign=DSA_Catchall_la.EN_cc.ROW&utm_content=deal4584&utm_term=_._ag_88010211481_._ad_398022934994_._kw__._de_c_._dm__._pl__._ti_dsa-406594358574_._li_1010781_._pd__._&matchtype=b&gclid=EAIaIQobChMI5p7VzI7V6AIVDImyCh31oAylEAAYASAAEgK9IfD_BwE

        var em = document.forms['Login']['email'].value; 
        alert(em);
        var atpos=em.indexOf("@");
          // Create a variable to return the numerical value of .
          // within the variable
          var dotpos=em.lastIndexOf(".");
          // Compare the numerical values
          if (atpos<1 || dotpos<atpos+4 || dotpos+2>=em.length)
                {
                alert("Not a valid e-mail address");
                //return false;
                } else if (em==null || em=="")
        {
            alert("Please enter your email adress");
            document.getElementById('e').focus();
            //return false;
        }

        var numb = document.forms['Login']['number'].value;
        if (numb==null || numb=="") {
            alert("Please enter your phone number");
            document.getElementById('num').focus();
            //return false;
        } else if (numb.length > 7) {
            alert("Phone number can't be more than 7 digits");
            document.getElementById('num').focus();
            //return false;
        }

    }

    function UpdateProfile() {
        myProfile = new Profile;
        myProfile.validateForm();
        if (myProfile.validateForm()) {
            myProfile.setProfile();
        } 
    }

    function displayProfile() {
        getProfile();
    }



</script>



</body>
</html>

you can read the local storage as following syntax.

/**here "key" is the local storage variable name where you have to store or fetch data from*/

localStorage.getItem("key");

inyour case:

var name = localStorage.getItem('name');

changes the value of an input field:

document.getElementById("FN").value = name;

if you want to remove the local stored data:

localStorage.removeItem("key");

if you want to clear all the data stored by your site:

localStorage.clear();

Note: You can only store data in local storage only in the form of string. If you need to store an object then you should convert (JSON.stringify(object)) the object to json and then store. You can parse the json to object (JSON.parse(json)) when you retrieves the value from local storage.

Demo is not working for some reason.

I did Some Changes copy HTML and JS code in your system, Hope this help. later you can modify however you want.

 class Profile { setProfile(n, a, e, t) { this.name = n; this.age = a; this.email = e; this.telephoneNumber = t; this.saveProfile(); } getProfile() { document.getElementById("FN").value = localStorage.getItem('name'); document.getElementById("age").value = localStorage.getItem('age'); document.getElementById("e").value = localStorage.getItem('email'); document.getElementById("num").value =localStorage.getItem('number'); } saveProfile() { let storeName = document.getElementById('FN').value; localStorage.setItem('name', storeName); let storeAge = document.getElementById('age').value; localStorage.setItem('age', storeAge); let storeEmail = document.getElementById('e').value; localStorage.setItem('email', storeEmail); let storeNum = document.getElementById('num').value; localStorage.setItem('number', storeNum); alert('Data saved in localStorage succussfully.;') } } function validateForm(e) { e = e || window.event. if (e;preventDefault) { e.preventDefault(); } else { e.returnValue = false. } var x = document;forms['Login']['fName'];value. if(x==null || x=="") { alert("Please enter your name"). document;getElementById('FN');focus(). //return false; } else if (x.length < 3) { alert("Password must be over 3 characters"). document;getElementById("FN").focus(). //return false } a = document;forms['Login']['ageField'];value. if(a==null || a=="") { alert("age can not be empty"). document;getElementById('age');focus(); //return false. } else if(parseInt(a)<12 || parseInt(a) > 95) { alert("age should be between 12 and 95"). document;getElementById('age');focus(). //return false. } var em = document;forms['Login']['email'].value; var atpos=em.indexOf("@"). var dotpos=em;lastIndexOf("."); // Compare the numerical values if (atpos<1 || dotpos<atpos+4 || dotpos+2>=em;length) { alert("Not a valid e-mail address"); //return false. } else if (em==null || em=="") { alert("Please enter your email adress"). document;getElementById('e');focus(). //return false. } var numb = document;forms['Login']['number'];value. if (numb==null || numb=="") { alert("Please enter your phone number"). document;getElementById('num');focus(). //return false; } else if (numb.length > 7) { alert("Phone number can't be more than 7 digits"). document;getElementById('num');focus(); //return false; } return true. } function UpdateProfile() { myProfile = new Profile(); if (validateForm()) { myProfile;setProfile(). } } function displayProfile() { m = new Profile(). console;log(m) m.getProfile(); }
 <;DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body onload="displayProfile()"> <h1> Profile </h1> Your Name <form name="Login" onsubmit="return validateForm()"> <input type="text" name="fName" id="FN"> <br> Age <br> <input type="text" name="ageField" id="age"> <br> Email <br> <input type="text" name="email" id="e"><br> Number <br> <input type="text" name="number" id="num"> <input onclick="UpdateProfile();" type="submit" name="sub" value="Update"> </form> </body> </html>

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