I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the next time they visit the page, their name will be displayed inside a span element.
Here is what I envision through pseudocode. I hope it clarifies my intention....
If a cookie named "name" exists, then display the stored information within a "span" tag
Otherwise,
Save the user's input as a cookie when they submit the form
(Note: My submit button is defined with type="submit")
@banana, I've made adjustments to my code to ensure alignment with all tag names and ids used. However, upon entering a name into the form, submitting it, and revisiting the page, nothing appears in the span element.
function setCookie(cname, cvalue, milliseconds) {
var d = new Date();
d.setTime(d.getTime() + (milliseconds));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
document.onload = checkIfCookieExists;
function checkIfCookieExists(){
var firstNameFromCookie = getCookie('firstName');
if(firstNameFromCookie == ''){
// cookie hasn't been set
}
else{
// cookie has been set
var display = document.getElementsByTagName('span')[0];
display.innerHTML = firstNameFromCookie;
}
}
function init(){
var firstName = document.getElementById('firstName').value;
var cookieExpieryTimeInMilliseconds = 1000 * 60 * 60; //1000 milliseconds * 60 seconds * 60 minutes - resulting in a cookie expiration time of 1 hour.
setCookie('firstName', firstName ,cookieExpieryTimeInMilliseconds );
}
window.onload = function(){
init();
};