Filtering Options in a Select Box with jQuery

Posted in . There are 0 responses.

I recently created a web form for a client that had two <select> elements, where the options presented to the user in the second <select> element were determined by the option selected in the first <select> element. It is a nifty feature to automatically filter options for the user, while providing validation at the same time. It can be a time saver for the user, even if it is only a matter of milliseconds. It also makes form validation stronger knowing that your user won’t get sloppy when filling out your form.

Take out the Guess Work

In my example, the first <select> element contains primary drink categories, and the second <select> element contains specific drinks that fall under one of those categories. It might be confusing to some users if they were to select “Juice” as their primary option and included in their secondary options were “Sam Adams” and “Coke”. Let’s assume that the user submitted the form, having selected “Juice” and “Sam Adams”. What the heck are you suppose with that data? You don’t know if the user wants some sort of juice or specifically “Sam Adams”. Why give the user an opportunity to make a mistake? Take the guess-work out of the form and make it as simple as possible for the user to interact with.

Using the jQuery library and the JavaScript provided in this tutorial, we will be able to validate these fields, making sure that the user actually selects a drink and flavor. We will also be able to filter flavor results based on what the user chooses for a primary drink. This means if the user selects “Soda” for a drink, we’ll only let them see the flavors: “Coke”, “Root Beer”, and “Sprite”.

Setting up the HTML

Before we get started, I’ve created a working example which combines all of the HTML and JavaScript I’ll be covering in this tutorial. It might also help to view the source code of the provided working example.

In the HTML below, I’ve created two <select> elements, each with several options. The first <select> element contains drink options for choosing a drink category. The second <select> element contains flavor of the drink. You’ll notice that in the <option> elements nested within the second <select> element we’ve also specified a class attribute which matches up with its parent category. We’ll be using the value of the options in the drink <select> element to match up with the classes in the flavor <select> element in our JavaScript.

We want the second <select> element to be disabled by default, but rather than specifying this in the HTML, we’ll use JavaScript. This way if the user has Javascript disabled, the form will still be functional.

<form>

  <label for="primary">Drink Category</label>
  <select name="primary" id="primary">
    <option value="">-- Select a Drink --</option>
    <option value="Beer">Beer</option>
    <option value="Juice">Juice</option>
    <option value="Soda">Soda</option>
  </select>

  <label for="secondary">Flavor Selection</label>
  <select name="secondary" id="secondary">
    <option class="" value="">-- Select a Flavor --</option>
    <option class="Juice" value="Apple">Apple</option>
    <option class="Beer" value="Budweiser">Budweiser</option>
    <option class="Soda" value="Coke">Coke</option>
    <option class="Beer" value="Corona">Corona</option>
    <option class="Juice" value="Grape">Grape</option>
    <option class="Juice" value="Leomonade">Leomonade</option>
    <option class="Beer" value="Miller">Miller</option>
    <option class="Juice" value="Orange">Orange</option>
    <option class="Soda" value="Root Beer">Root Beer</option>
    <option class="Beer" value="Sam Adams">Sam Adams</option>
    <option class="Soda" value="Sprite">Sprite</option>
  </select>

</form>

Making it Cool with JavaScript

This tutorial uses the jQuery library to make life easier for our validation and filtering needs. I’m a big fan of jQuery and I highly recommend it. I realize that using jQuery can add a significant amount of page load time. While we want to be able to validate the form, we also don’t want to have the user wait for JavaScript to load before they start filling out the form. This is why I prefer placing JavaScript right before the closing </body> tag. The first thing we need to do is to include the jQuery library. You can download and host it yourself, or you can do what I do and let Google host it for you.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

All of our JavaScript will be in a self-contained function filterSelectBox(). In our function, the first thing we’ll do is disable the second select element. We’re using JavaScript to do this, rather than HTML, in case the user has JavaScript disabled. If we used HTML and the user had JavaScript disabled, the drink element would never become enabled. We’ll also create an array of all the drink options from the second <select> element. Then we’ll assign it to a variable. We’ll be filtering out options in this array based on the <option> the user chooses from the first select box.

(function filterSelectBox() {

  $("#secondary").attr("disabled", "disabled");

  var arr = $.makeArray(document.getElementById("secondary"));

})();

Now that we have our array assigned to a variable, we want to create an event handler that executes whenever the user changes the state of the first <select> element (which has an id of “category”). In this event handler, we also want to define a couple more variables. The first variable, primaryCat will equal the value of the first <select> element, and the second variable, txt equals an empty string.

$("#secondary").change(function() {
    var primaryCat = $("#primary").val(),
        txt = "";
});

In the following if statement, we want to check to see if the user has selected an option (technically, an option with a value) or not. If the user has, then it will enable the secondary (drink) select element, otherwise, it will disable it.

if (primaryCat !== "") {
  $("#secondary").removeAttr("disabled");
} else {
  $("#secondary").attr("disabled", "disabled");
}

If the user has selected a valid drink category, we want to go through every option in the array of flavor options we created earlier and only keep ones where their class matches the value of the drink option. After we’ve filtered the drink options, we want to flush out all of the current flavor options and replace them with the new ones. We’re only keeping results where the options in the drink select element whose class is equal to the value of the parent category. After we’ve filtered the options, we’re removing all the current options and appending the string of new options to the drink select element.

$.each(arr, function() {
  var subCatClass = $(this).attr("class"),
    subCatValue = $(this).val();
  if (subCatClass === primaryCat) {
    txt += '<option class="' + subCatClass + '" value="' + subCatValue + '">' + subCatValue + '<\/option>';
  }
  $("#secondary").empty().append(txt);
});

This working example combines all of the HTML and JavaScript I described in this tutorial.

Wait a minute, is it really worth the hassle?

I’d like to assume that the average user is competent enough to fill out a form correctly, but you and I both know that a lot of users are not. At the very least, you should probably be using some sort of basic form validation, whether it be client-side, server-side or both. It doesn’t take too much more time or effort to make things a littler easier on the user by filtering their options — especially if there are a lot of options to choose from. You’re also saving yourself time and energy by applying form validation because you won’t have to try and sort out faulty submissions.

Mobile Website Design & Development

Posted in . There are 0 responses.

Note: This article was originally posted at the Dyn Inc. Journal. If you have any comments, please feel free to post them there.

We recently unveiled DynStatus, the new home for Dyn Inc. related status reports and updates. We realize that a lot of our customers relying on our service are constantly on the go and don’t always have the luxury to be able to check our system statuses from a desktop computer. We thought we’d make life a little easier for them and create a mobile version of the site.

Mobile Devices: The Wave of the… Present

In 2006, PC World reported that there will be at least four billion mobile subscribers on the planet by 2010. To put it bluntly, that’s a lot of people! It should come as no surprise that designing for mobile devices has become increasingly popular. However, there is still a lot of ambiguity as to how to design and develop for them. My hope is that this article will help clear up some of the questions faced when designing for mobile devices.

Creating a website for a mobile device is very different than creating a website for a traditional desktop computer. Some of the differences are obvious such as screen size and download speeds. Then there are the not-so-obvious such as coding methods and implementation. Unfortunately, there is no best way to design a mobile website. There are good practices to follow, but because of the lack of standards supported by all of the different devices there is no one simple solution.

General Guidelines

Just like designing your first website for a normal size monitor, designing your first mobile website can be an intimidating task. Just as much planning needs to go into it, if not more. Having gone through the experience, here are some simple guidelines I can recommend.

Keep it Flexible

Screen sizes vary from device to device, especially on devices like iPhones where you can view it vertically or horizontally. I recommend designing with a fluid layout. Avoid specifying font sizes using ems, pixels, or percents. Instead use CSS values such as medium or small. Using a completely fluid layout will ensure maximum compatibility between devices.

Do Not Use Unnecessary Images

This ties in a little bit with using flexible layouts. Keep images to a bare minimum. In fact, I’d recommend not using them at all if you can avoid it for several reasons:

  1. It will greatly reduce complex layouts and designs
  2. It will decrease the number of HTTP requests and save your users on bandwidth, which matters much more on a mobile device then it does on a desktop computer
  3. If you use an image, make sure you have the alt attribute specified

Also, I’d stay away from using the background-image property. It’s supported by the XHTML Mobile Profile 1.0 Doctype, but some phones will not support it.

Access Keys

Screenshot of status.dyn-inc.com/mobileI find touch screen devices to be hypersensitive and not always accurate when touching the screen with your finger or stylus. On most mobile devices, using the accesskey attribute on links will allow you to access the link just by pressing the number or letter on the keypad. When doing this, it might help if you try to make it obvious to the user that they can use access keys. If you look at the image on the right, you see that I singled out the “H” in Home so that users can figure out that pressing “H” will take them back to the Home Page.

Testing

You might think I’d say test your mobile site on as many devices as possible, but I’m not going to. There are just so many devices available and its unfeasible to test them all out. Aside from that, who has the money to go out and purchase a number of devices? I recommend testing in the typical browsers such as Firefox, Internet Explorer and Safari. You’ll also want to test your site on two or three mobile devices as well as on the Lynx web browser which is a text-only browser. If your site looks good on Lynx, then it should degrade nicely on just about any mobile device.

Learn More

Despite the complications of designing for mobile devices, there are some great resources available. A great book that I cannot recommend enough is Mobile Web Design by Cameron Moll. It deals with just about everything, including development methods, testing and validating, and using advance features such as Flash, RSS and AJAX. There are also some great references made available by the W3C, such as Mobile Web Best Practices 1.0 and CSS Mobile Profile 2.0.

KISS (Keep it Simple Silly)

If there was only one thing I would want you to take away from this article, it would be keep mobile websites as simple as possible. If someone is looking at a website on their mobile device, chances are they want the content fast and easy to read. The user doesn’t want to have to wait for long downloads, deal with unnecessary images, and mentally process complex layouts. If you can remember this, then all of the other technical challenges, such as coding methods and implementation will become less crucial.

Hosting Switcheroo

Posted in . There are 0 responses.

I’m continuously being challenged at my new job and I’m loving it. As with any job, it’s always good to expand your knowledge as it makes you a flexible, well-rounded asset. Lately, I’ve really been pushing myself to learn more about server basics.

Here we go…

A couple of weeks after I started, we released a new service Spring Server VPS. In short, its a virtual hosting solution that offers some advance features such as access to your own operating system, IPv4 and IPv6 Internet access with reverse DNS, and multiple Tier-1 bandwidth providers. I obtained a Spring Server so that I could learn more about our services and also learn how to setup a server.

I have been using Dreamhost to host this site (along with a couple of other side projects) and all-in-all I have been pretty happy with them. They’re quick to respond when I have a question, and I don’t have to worry about setting up the server and tweaking things behind the scene. However, their up-time was sometimes flaky—though I’ll admit, never to a point where that made me want to switch hosts. Still, I wanted to take on the challenge of setting up my own server and setup the hosting on it.

Not in my skill set

I can design websites and write lines of code until I’m blue in the face (which has happened on occasion), but when it came to this area, I had very little knowledge and would be deemed useless if ever approached for help. That being said, I can’t believe how incredibly easy it was to setup my Spring Server. Following these instructions, I was running a simple static website in about 30 minutes. To set it up specifically for my site involved a little more work, which I’ll talk about in future postings.

In conclusion

It’s definitely overkill hosting my website on a Spring Server, as I hardly receive the traffic that they are built to handle. It does load about three seconds faster, which is pretty cool. Soon, I’ll be writing up an entry or two as to how to setup a website, managed by Textpattern, on a Spring Server (though I suppose it would work on just about any server, as it’s not DynDNS.com or hardware specific).

Why use Doctype XHTML Strict

Posted in . There are 0 responses.

Note: This article was originally posted at the Dyn Inc. Journal. If you have any comments, please feel free to post them there.

Recently, we unveiled a redesigned version of our Dynect Website. Within a three week time-table we updated existing content, added new content, and gave the design a major overhaul. This is the first of our websites to use strict XHTML. Its easy to get stuck using transitional XHTML, especially when doing a redesign because it is not always easy to convert legacy markup to comply with Strict requirements. However, using the Strict Doctype carries a lot of benefits with it. It encourages separation of structure and content, has better cross-compatibility between web browsers, and enforces accessibility to users with special needs.

Separation of Structure and Content

Among web designers and developers, Separation of Structure and Content is one of those phrases that is thrown around as an argument supporting strict XHTML markup. However, if you’re not a designer/developer, its meaning can seem ambiguous. Simply stated: Structure refers to the way information is presented to the user while Content refers to the information that is being presented.

Think of structure as being the skeleton and organs of the website. It includes everything from the layout of a website (skeletal frame), right down to what size font the copyright notice should be (organs with functions). Content is the reason why the user is visiting your website in the first place. Whether it be visual or text, it is the information being presented to the user. Use this page as an example. The structure encompasses the layout, what colors and fonts are used, and layout-related images like the company logo. These elements are consistent from page to page and rarely changes. The content is this blog post you are reading — the title, the article, the comments, etc. This content changes on every page.

There are several advantages to separating structure and content. First, it makes it easier to maintain a website as content is added, removed or modified. This is especially true if the website is using a content management system. Second, it greatly reduces file sizes because less markup is being used, thus making page load times faster. And third, it makes for better SEO which will greatly help your search engine rankings.

Better Cross-compatibility

Unfortunately, not everyone using the Internet is using the latest and greatest browsers available, such as Firefox or Safari. Having to cater to older, non-standard-compliant browsers (read: Internet Explorer 6) can make the development phase a little more of a challenge. Using strict XHTML drastically helps protect programmers from using invalid coding techniques, such as improperly or not closing HTML elements. Some browser rendering engines are more lenient than others, but using valid HTML will ensure that a web page will look similar across all browsers. Some other requirements of strict XHTML are no capital letters may be used in elements, and no depreciated elements or attributes may be used as well.

Enforcing Accessibility

These days, accessibility is becoming more and more important—just look at the lawsuit that Target just settled. Strict XHTML helps enforce accessibility guidelines. An example is using the alt attribute for image elements. The alt attribute contains provides alternative text describing the image. This is important for two reasons: 1) If the url to the image is broken, it will display the alt text in its place and 2) If you have a blind user using JAWS) or some other screen reader to navigate the website, it will present the alt text audibly or through a braille display.

Additional Resources

The examples given above really only scratch the surface of this topic. There are a lot of resources available regarding the use of strict XHTML. I’ve put a short list together of articles that will help shed more light on the advantage to using strict XHTML and XHTML in general.

My Thoughts on Blueprint

Posted in . There are 0 responses.

Lately, there seems to be a lot of hype about the new CSS framework Blueprint. I think it’s great that Olav Bjorkoy has taken the time to create the perfect CSS framework. What makes it perfect? Every column, line-height, header, and font-size in general is perfectly calculated. It even comes with a test grid, a typography example, and a tutorial. It truly is beautiful to see it in action, and it looks really sharp.

Having said that, I don’t think Blueprint is very practical. Every website is different and I don’t see how having a CSS framework can make things go faster. If anything, I would think it would be more of a hindrance, having to rename styles, or reformat them to fit the design of the site. I’m not saying there aren't exceptions to using a CSS framework. But where CSS plays such an integral roll in web design these days, I think design needs more than a generic CSS framework, no matter how perfect it may be. I think it would be faster, more semantic, and more efficient to just start from scratch.

Nathan Smith said it best:

For what it's worth, Blueprint is very well thought out. If I ever need to put together a news oriented website on a 14 column grid, it’d be a great stating point. However, I’d rather let the overall requirements of a project dictate whether or not a framework is used, as opposed to forcing a square-peg / round-hole scenario.

If everyone starts using Blueprint, are all of our websites going to start looking the same? This would cause design and technology on the web to regress. People would no longer bother to try to break the mold because it wouldn’t fit within the universal framework. I realize I’m probably over-exaggerating here, but I think you can see my point.

Back to top