Skip to content
Advertisement

Enabling 4-digit pincode autofill using cookies

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:

JavaScript

HTML:

JavaScript

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 the if statement 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.

Advertisement

Answer

For cookies I use my “simpleCookie” object with the set / getVal methods to read or save a cookie.

ex:

JavaScript

this object is achieved via an IIEF function, and I strongly advise you to use the mozilla documentation

Since automatic form validation exists, I no longer use a text box to indicate an input error, but I have diverted its “normal” use a bit because I find it very restrictive, as you will see in my code.

When at the base of your question, you just have to find a match between the name entered and a possible cookie with the same name, then save this cookie if the form is valid.

Oh, and I also put some css to simplify writing html (no more need for <br>)

JavaScript

simpleCoolie.js :

JavaScript

login_form.js :

JavaScript

In 2009, session/localStorage arrived, which can replace cookies, especially for this kind of use.

To not have to redo all the previous logic, I created here a module called pseudoCookie which actually uses localStorage

here is the complete code to test with it:

JavaScript

and the part to change in JS:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement