I'm working on a quiz app as part of my college course and have ran into a bit of a roadblock. The code below is for few functions I've wrote. These are supposed to take the user input from the name and email fields, validate the email and store the name as a cookie to be displayed on another page.
I've got this working for the most part, but I'm having trouble getting the stored cookie value to display correctly. It is loading, but is showing as undefined=ryan. If I type a longer name, less and less of the string is displayed. I think there's an issue with the section where I've tried to split the string, but I can't figure it out for the life of me.
Any help or advice would be greatly appreciated.
Thanks :)
function setCookie(cname, cvalue)
{
let userValue = document.getElementById("email").value;
let pos_of_at = userValue.indexOf("@");
if (userValue == " " || pos_of_at<0)
{
alert("You must enter a valid email address");
document.getElementById("email").focus();
}
else
{
cvalue=document.getElementById("userName").value;
document.cookie= cname + " = " + cvalue + ";";
window.location.href="/quiz.html"
}
}
function getCookie(cname)
{
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i =0; i<ca.length; i++)
{
let c = ca[i];
c = c.trim();
if (c.indexOf(c) ==0)
{
return c.substring(name.length, c.length);
}
}
return "cookie not found";
}
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Figured it out. Issue was the checkCookie function.
Was
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Should have been
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie();
}