Thursday, January 23, 2025

JavaScript Class: How Can I Set A Cookie Based On A User’s Selection On A Form?

As a web developer, you may want to allow your site’s visitors to make a choice on a form, then direct them to a specific page based on their selection. This tutorial will show you how to, for example, allow your users to select the type of mobile device they are using, then go to the page for that device thereafter, based on their selection–using cookies and JavaScript!


In our recent article entitled How Can I Detect the iPhone & iPad’s User Agent? we discussed how to detect if a user is accessing your web page using an iPhone or iPad, and redirect that user to a page based on their specific device. In this article, we’re going to show you how to, instead, allow the user to specify their device on their own via a small form on your page, and based on their selection, they will be directed to the specific page for their device. Once they have made their selection, whenever they revisit your page, they will automatically be redirected to that page.

What Are Cookies, and Why Should I Care?


Cookies is the name given to the data that can be stored in your web browser whenever you visit a website. Although that may sound like a privacy violation, the type of data that can be stored is limited, and can’t be shared with other sites, so you’re pretty safe, and so are your site’s visitors. Most sites use cookies for tracking where you’ve been on their site, so you can be shown new posts, new content, etc. based on the time of your last visit. In our example, we will simply be storing the user’s selection from the form they filled out on your page. It will look like this:

Please choose your mobile device:
iPhone
iPad
Android
Palm


Note that you can choose the names of the selections, as well as the field name, but you will need to also change those names (and URLs) within the JavaScript file, which we will get into next.

How Do I Use JavaScript To Do That?

Rather than have you do all the dirty work, we have a JavaScript file that you can attach to your web page that does it all for you. You can download all the files used in this tutorial here. If you open the cookieRedirect.js file, this is what you will see:


var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function getCookieVal (offset) {
var endstr = document.cookie.indexOf (“;”, offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + “=”;
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(” “, i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + “=” + escape (value) +
((expires == null) ? “” : (“; expires=” + expires.toGMTString())) +
((path == null) ? “” : (“; path=” + path)) +
((domain == null) ? “” : (“; domain=” + domain)) +
((secure == true) ? “; secure” : “”);
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() – 1);
var cval = GetCookie (name);
document.cookie = name + “=” + cval + “; expires=” + exp.toGMTString();
}

var favorite = GetCookie(‘device’);

if (favorite != null) {
switch (favorite) {
case ‘iPhone’ : url = ‘iphone.html’; // change these!
break;
case ‘iPad’ : url = ‘ipad.html’;
break;
case ‘Android’ : url = ‘android.html’;
break;
case ‘Palm’ : url = ‘palm.html’;
break;
}
window.location.href = url;

}

Before we go any further, you can see this script in action here. As you can see, once you have made your selection and have refreshed the page, you are automatically taken to the appropriate page. Within the script, the only things you will need to change are the names and URLs. For instance, to change the selection from “device” to “animals” you would simply make those changes within the script as shown:


var favorite = GetCookie(‘animal’); // we changed this

if (favorite != null) {
switch (favorite) {
case ‘cat’ : url = ‘cat.html’; // and this
break;
case ‘dog’ : url = ‘dog.html’; // and this
break;
case ‘gerbil’ : url = ‘gerbil.html’; // and this
break;
case ‘gopher’ : url = ‘gopher.html’; // and finally this
break;
}


And in our form shown above, we changed it to the following:

<form>
<table><tr><td>
Please choose your Favorite Pet:<br>
<input type=checkbox name=”cat” onClick=”SetCookie(‘animal’, this.name, exp);”>Cat<br>
<input type=checkbox name=”dog” onClick=”SetCookie(‘animal’, this.name, exp);”>Dog<br>
<input type=checkbox name=”gerbil” onClick=”SetCookie(‘animal’, this.name, exp);”>Gerbil<br>
<input type=checkbox name=”gopher” onClick=”SetCookie(‘animal’, this.name, exp);”>Gopher<br>
</td></tr>
</table>
</form>

This little JavaScript tidbit can be used to save the choices your visitors make, and use that selection to save them the hassle of having to make their selection again. Useful for mobile sites, hobby sites, pet sites–the list is infinite.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured