I have a simple form where one needs to enter a 4-digit PIN code. However, I would also like to autofill that PIN code when the user comes back to the website again, using JS cookies.
JS:
function loginCheck() {
var pinCode = document.getElementById("pinCode").value;
if (pinCode.match(/^[0-9]+$/) != null) {
if (pinCode.length == 4) {
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";"
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var pinCode = document.getElementById("pinCode").value;
var userPIN = getCookie("userPIN");
if (userPIN != "") {
pinCode.value = userPIN;
} else {
setCookie("username", userPIN);
}
}
checkCookie();
} else {
document.getElementById("rightorwrong").innerHTML = "Not 4 digits!";
}
} else {
document.getElementById("rightorwrong").innerHTML = "Not a number!";
}
}
HTML:
<div id = "validation">
<form id = "validationForm" target = "frame">
<fieldset>
<label for = "pass">Password:</label><br />
<input type = "text" id = "pass" name = "pass" /><br />
<label for = "pinCode">4-digit PIN:</label><br />
<input type = "text" id = "pinCode" name = "pinCode" /><br />
<input type = "submit" value="Log In" onclick = "loginCheck()" />
</fieldset>
</form>
</div>
<p id = "rightorwrong"></p>
I'm aware of a few things that are wrong about this code.
- in the
checkCookie()function, if the user has a cookie stored, then I'm not entirely sure how to retrieve the PIN they first inputted. - Defining functions inside functions, and calling them by simply doing
checkCookie();and nothing else, is generally bad practice. - When I run
checkCookie();it only does the first part of theifstatement and not the second part. I'm not sure why and I couldn't figure this out. - The code in general may have some errors. I modified a cookies script from here but it doesn't seem to work.
I'm new to the idea of cookies, and am still trying to learn them. A step-by-step explanation would be more helpful.
Help would be greatly appreciated, TIA.