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:

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:

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.