Skip to content Skip to sidebar Skip to footer

Javascript Login, Cookies

can anyone help me with my homework please?

Solution 1:

Inside member() function, you can access the elements with their ids, then get the values and finally check for them being valid:

functionmember() {
    // Get the elementsvar user_input = document.getElementById("txtuser");
    var pass_input = document.getElementById("txtpass");

    // Get their valuesvar user_value = user_input.value;
    var pass_value = pass_input.value;

    // Validate values, this is up to youif ( /* this is your homework */ ) {
        // Here values are OK, save a cookie with the usernamesaveTheCookie(user_value);
        returntrue; // Form is OK
    }
    else {
        // Form is wrongreturnfalse;
    }
}

You can store cookies with some function like this:

functionsaveTheCookie(value) {
    var today = newDate(); // Actual datevar expire = newDate(); // Expiration of the cookievar cookie_name = "username_form"; // Name for the cookie to be recognizedvar number_of_days = 10; // Number of days for the cookie to be valid (10 in this case)

    expire.setTime( today.getTime() + 60 * 60 * 1000 * 24 * number_of_days ); // Current time + (60 sec * 60 min * 1000 milisecs * 24 hours * number_of_days)document.cookie = cookie_name + "=" + escape(value) + "; expires=" + expire.toGMTString();
}

To get the value of the cookie:

functiongetTheCookie() {
    var cookie_name = "username_form";
    var return_value = null;

    var pos_start = document.cookie.indexOf(" " + cookie_name + "=");
    if (pos_start == -1) document.cookie.indexOf(cookie_name + "=");

    if (pos_start != -1) { // Cookie already set, read it
        pos_start++; // Start reading 1 character aftervar pos_end = document.cookie.indexOf(";", pos_start); // Find ";" after the start positionif (pos_end == -1) pos_end = document.cookie.length;
        return_value = unescape( document.cookie.substring(pos_start, pos_end) );
    }

    return return_value; // null if cookie doesn't exist, string otherwise
}

Note that I DID NOT test this, it's an idea for you to start. You still have to check the form, set the cookie and retrieve it when loading pages (including setting the HTML of a DOM element in the onload event in the body tag). Good luck!

Post a Comment for "Javascript Login, Cookies"