Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

September 27 2013

14:01

Web Design Concepts to Entice User Interaction

Advertise here with BSA


Landing pages and social websites thrive on user interaction. It is the grinding mechanism which keeps people visiting your webpage over and over again. How you design an interface can say a lot about how people should maneuver through menus, links, buttons, and other similar page elements. Each solution is different and there certainly isn’t any prominent correct answer.

In this article I want to go over some more popular web design concepts for creating alluring interfaces. You want visitors to be swept away by the design and practically fall in love with your website. A beautiful design coupled with a beneficial experience is what can help your web application or website layout stand apart from the rest.

Relating to the Interface

The key to any enticing interface is to make the user wants to interact with your website. Obviously the primary reason should be their interest in your product or service… you want people registering an account because they actually want to. But it helps to give them a little incentive by designing catchy interfaces which practically sell themselves.

pinterest create a new board form ui design screenshot

Consider the newer photo sharing startup Pinterest as one example. All of their forms use big readable typography with CSS3 gradients on the buttons and input fields. Also the glowing borders are a nice touch to inform the user which field is currently highlighted. Even more importantly is that all the page elements blend so nicely into the website color scheme. Interacting with forms on Pinterest feels completely natural – as it should be on any website.

tumblr website buttons input fields new post screenshot

Tumblr is another case example where the buttons and input fields have been carefully crafted to blend nicely with the layout. The uniform posting box looks very similar for any type of content including photos, videos, or even plain text. The more you can blend forms into your website, the more relatable they will appear to your visitors.

By creating this natural connection it evokes a sense of safety and commitment. People want to fill out your forms and interact with the page because the elements don’t appear like they’ve all been thrown together at the last minute. Put in some TLC to your website’s form design and I promise it will pay off in the long run.

Design Elements that Pop

Similar to relatable interfaces we also want a design which can practically jump off the page. To phrase this another way, visitors should be able to determine which page elements are interactive and which ones aren’t. You can accomplish this task through all sorts of different methods like border styles and box shadows.

rightsignature homepage layout css3 design screenshot

The homepage design for RightSignature is one good example because of their advancing design trends using CSS3. The top navigation and right sidebar areas remain fixed on the page, as they also include the most interactive features. The visitor can scroll through all of this information while simultaneously registering for a new account. Also take note the registration form only requires two simple fields for the username and e-mail address. A lower barrier-to-entry will get a lot more signups because it takes less time and less hassle from the user’s perspective.

dribbble textured popular shots layout design

I am also a big fan of Dribbble’s layout because of the many design changes which have taken place over the years. Dribbble has always been using a very similar layout style, except the colors and textures have been tweaked ever-so-slightly. You could even incorporate the idea of A/B testing into your website to determine which colors or UI designs would be most appealing to your audience.

Readable Content

It might go without saying, but readability is a huge factor to user interaction. People keep using content-based websites and social networks because of the ability to skim content and quickly recognize its purpose. Consider a homepage dashboard with all the latest news from a user’s feed. How can they quickly determine between a website blog post, a user status update, or a new photo album?

medium blogging posts users homepage layout screenshot

The new micro-blogging platform Medium has grown very popular in a short period of time, especially among tech-lovers and startup enthusiasts. Each blog is made to conform into Medium’s typical layout design which utilizes big typography – nice and easy to read even at a distance from the monitor. This not only makes people want to write more articles, but it also gets readers more willing to stick around and read through a post if the content is easily legible.

etsy products list web design interface layout

A somewhat related yet different circumstance may be found on Etsy. People come on here looking for custom hand-made trinkets or neat little gifts for friends. The product gallery is designed in a way that you can quickly check out what is for sale, how much it costs, who the seller is, and other types of related items for sale. It is one of my favorite growing marketplaces because the design is so eccentric that it immediately catches your attention. Also the products are generally unique and often not sold anywhere else, so it’s a marketplace of rare items with an extremely intuitive process for buyers and sellers.

Points and Profile Badges

Not all websites have the option of creating profile pages for each user. This is typically common amongst social networks and communities which thrive on user-driven content. Applying unique rewards such as badges or points will get people much more interested in using your product. Stack Overflow is one such example where you can earn points by linking to threads, answering questions, or even asking questions of your own.

github user profile kyle bragger screenshot stats repositories

Another great example can be found on the Github profile pages. Here you can see every repository created by a certain user, along with their work done in other people’s repositories. You can also find stats like their follower count and the total number of starred repos. Point systems work best if you build them on top of the existing website functionality. It is a motivator which gets people pushing to contribute more content and grow their profile on your website.

Uniform Layouts

One final piece of advice for improving user interaction is to get all your pages designed in the same fashion. Uniformity is very important as I outlined in the first section of this article. As people use your website more frequently they become accustomed to the interface. A uniform design helps people grow to expect certain interfaces to behave in a certain way, and people will gradually learn all the little tricks of how your website works.

reddit social news community simple design homepage layout

Possibly one of the largest case study examples would be on Reddit. This social news community allows people to register an account and submit, vote, or comment on news stories. It has scaled tremendously over just a few years as subreddits have grown proportional to the userbase. As more people get comfortable with how the system works, it becomes easier for them to engage deeper into the website and contribute even more content. Think about this concept for your own website and how you might implement uniform design techniques to improve the overall user experience.

Closing

These are just some examples of design trends you may try in your layouts. I have played with a number of fantastic web applications, and the best ones have always been designed with the user in mind. Focus on the end user and consider if your webpage is optimized for the easiest frontend performance. Additionally if you have similar ideas or suggestions on usable interfaces feel free to share with us in the post discussion thread.


Advertise here with BSA

August 22 2013

13:58

How To Make a Custom HTML5 Select Menu with Selectize.js

Advertise here with BSA


Detailed and customized input fields have been a great focus of modern web development. The jQuery library along with similar open source projects have provided a framework to build with. It has lead to numerous advances within the field of user interface design. Especially for customizing the typical “default” components in form elements.

In this tutorial I want to introduce the Selectize plugin for jQuery. It allows developers to greatly alter the presentation of input fields related to select menus and tag-formatted text fields. This can provide a tremendous benefit on projects where you need a cleaner, updated interface. It is a fairly straightforward process and shouldn’t take more than 60 minutes to create. Take a peek at my live demo to see what we are making.

jquery selectize custom select menus html5 demo

Live DemoDownload Source Code

Getting Started

First we need to download a copy of Selectize and keep the local CSS/JS files stored in the same location. You can download this archive from the Selectize.js Github repo which also includes a few sample demos. All we need is selectize.min.js and selectize.css. Copy these files into a new folder /js and /css, respectively.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Customized Input Select Menus - Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/style.css">
  <link rel="stylesheet" type="text/css" media="all" href="css/selectize.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/selectize.min.js"></script>
</head>

You should notice I downloaded a local copy of jQuery to store in the same /js folder. Also I created another stylesheet named style.css which helps to structure the website layout. Overall there are only 4 resource files and jQuery is the only dependency we need.

Now Selectize.js offers a multitude of various setups to choose from. The default configuration requires no parameters at all. But this plugin is heavily documented with all of the parameter options you could include, and what they do. I want to get us started with two basic elements inside a sample HTML form – but remember this link when you need to go back and customize some functionality.

Inner Body Content

The form elements are pretty standard and I am using jQuery e.preventDefault() to stop the form submission. Each .formrow class is used to split up the content into horizontal sections. We only need to apply selectize() onto the select menu and the tags menu.

  <form id="testform" method="post" action="#">
    <div class="formrow">
      <label for="name">Name:</label>
      <input type="text" id="name" class="basictxt" placeholder="Your name...">
    </div>
    
    <div class="formrow">
      <label for="email">Email:</label>
      <input type="text" id="email" class="basictxt" placeholder="Your email...">
    </div>
    
    <div class="formrow">
      <label for="subject">Subject:</label>
      <select id="subject">
        <option value="1">General Inquiry</option>
        <option value="2">Advertising</option>
        <option value="3">Press</option>
        <option value="5">Account Problems</option>
        <option value="4">Content Submission</option>
      </select>
    </div>
    
    <div class="formrow">
      <label for="tags">Tags:</label>
      <input type="text" id="tags" value="website,graphics,question">
    </div>
    
    <div class="formrow">
      <label for="message">Message:</label>
      <textarea class="basictxtarea" id="message"></textarea>
      <input type="submit" class="large button" value="Send Message">
    </div>
  </form>

After this initial starting block you’ll notice that I have included both the dropdown and the text-based tags input. Selectize handles this interface beautifully and it is worth the effort to get things setup if you need this functionality in your script. The ID #subject and #tags will be used for targeting the element itself.

Internal option values from the select menu can be determined using simple jQuery. This means you can pass the same values into your form through Ajax or regular user submission. But even using the tag field we can still get return values naturally after the form is submitted. My example here provides the default value=”website,graphics,question” which can be updated as the user appends more tags onto the list.

CSS Styling

The default Selectize styles are very important and should always be included within the page header. These will create the tag styles and other various input select features. If you wish to customize them, check each item’s scope within the CSS file and overwrite the properties in your own stylesheet.

/* form styles */
.basictxt {
  display: block;
  padding: 7px 8px;
  width: 550px;
  color: #555;
  font-size: 1.5em;
  border: 1px solid #ccc;
  font-family: Helvetica, Arial, sans-serif;
}

.basictxtarea {
  display: block;
  padding: 8px 10px;
  width: 600px;
  height: 115px;
  color: #555;
  font-size: 1.6em;
  border: 1px solid #ccc;
  margin-bottom: 14px;
  font-family: Helvetica, Arial, sans-serif;
}

.selectize-control { width: 60%; }

Many of these properties are not useful aside from resetting basic HTML forms. The .selectize-control class is applied onto every element running this jQuery function. Normally the input fields are using display: inline and the width can appear too short for the inner text. I am using 60% because it fits nicely into the layout, however you should customize this value to whatever suits your design.

.button::-moz-focus-inner {
  border: 0;
  padding: 0;
}

.button {
  display: inline-block;
  *display: inline;
  zoom: 1;
  padding: 6px 20px;
  margin: 0;
  cursor: pointer;
  border: 1px solid #bbb;
  overflow: visible;
  font: bold 13px arial, helvetica, sans-serif;
  text-decoration: none;
  white-space: nowrap;
  color: #555;
  background-color: #ddd;
  background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,1)), to(rgba(255,255,255,0)));
  background-image: -webkit-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0));
  background-image: -moz-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0));
  background-image: -ms-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0));
  background-image: -o-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0));
  background-image: linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0));
  -webkit-transition: background-color .2s ease-out;
  -moz-transition: background-color .2s ease-out;
  -ms-transition: background-color .2s ease-out;
  -o-transition: background-color .2s ease-out;
  transition: background-color .2s ease-out;
  background-clip: padding-box; /* Fix bleeding */
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, .3), 0 2px 2px -1px rgba(0, 0, 0, .5), 0 1px 0 rgba(255, 255, 255, .3) inset;
  -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, .3), 0 2px 2px -1px rgba(0, 0, 0, .5), 0 1px 0 rgba(255, 255, 255, .3) inset;
  box-shadow: 0 1px 0 rgba(0, 0, 0, .3), 0 2px 2px -1px rgba(0, 0, 0, .5), 0 1px 0 rgba(255, 255, 255, .3) inset;
  text-shadow: 0 1px 0 rgba(255,255,255, .9);
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.button:hover {
  background-color: #eee;
  color: #555;
}

.button:active {
  background: #e9e9e9;
  position: relative;
  top: 1px;
  text-shadow: none;
  -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .3) inset;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .3) inset;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .3) inset;
}

.button[disabled], .button[disabled]:hover, .button[disabled]:active {
  border-color: #eaeaea;
  background: #fafafa;
  cursor: default;
  position: static;
  color: #999;
  /* Usually, !important should be avoided but here it's really needed :)  */
  -moz-box-shadow: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
  text-shadow: none !important;
}

.button.large {
  padding: 12px 30px;
  text-transform: uppercase;
}

.button.large:active {
  top: 2px;
}

If you wish to duplicate the submit button style I copied over the important properties above. This original interface scheme comes from a design on Codepen with many other CSS3 effects. The button design is fantastic and it should blend nicely with any layout. Other styles are just common CSS resets and so we should move on to the final JS syntax.

Selectize.js with jQuery

As usual we need to create a script tag at the bottom of the page, before the closing </body> tag. This will contain the JS code to prevent form submission, as well as the selectize functions. If you need the form to work properly then remove this $(‘#testform’).submit() function entirely.

$(function() {
  $('#testform').submit(function(e){
    e.preventDefault();
  });
  
  $('#subject').selectize({create: true});
  $('#tags').selectize({    
    delimiter: ',',
    persist: true,
    create: function(input) {
      return {
        value: input,
        text: input
      }
    }
  });
});

The first method is targeting the select dropdown menu. It runs selectize({create: true}) which passes the create parameter. When true, this allows users to actually type in their own value for the select menu. It is very unique and may be helpful in some specific instances.

Looking over at the tags function I am passing quite a few more options. When creating a new tag we need to call a function which can return these values to be added back to the input field. Since this is a text field it will behave differently than a select menu. The delimiter string is what separates all these tags when passed into the form as one long value. Also persist will force all user-added values to stay in the menu as a potential choice until the page is refreshed.

There are so many other parameters you can include which provide a heck of a lot more functionality. Many of these options are also callbacks, which means you can trigger a new function once a certain event has happened(like the user clicks an option). And if you really want to get technical look through their plugin documentation for creating your own extended effects.

jquery selectize custom select menus html5 demo

Live DemoDownload Source Code

Final Thoughts

Referencing jQuery plugins for your website design can be a huge time saver. I have been thoroughly impressed with many newer plugins that have been released over 2012 and 2013. There is never a shortage of new ideas when developers are willing to build these on top of existing open source platforms. I do hope this tutorial will prove useful in future web projects. Additionally feel free to download a copy of my source codes for easy-access to the sample project.


Advertise here with BSA

Sponsored post
soup-sponsored
04:52

August 06 2013

14:09

How To Build a Range Slider Input with jQuery UI

Advertise here with BSA


Looking at the HTML5 range input element you can see a number of advancements. Forms are able to take in restricted information from users sliding between number segments. But unfortunately these HTML5 inputs are only supported in modern browsers. So although there are a few limitations we can try to work around them.

I want to demonstrate how to build a more customized version of the range slider using jQuery UI. The slider widget is a part of the jQuery UI core library so it comes prepackaged with the script. This makes it really easy to play with because the documentation has been well-sourced and easy to consume. Check out the live copy of my sample demo to see what we are creating.

jquery ui sliders inputs form

Live DemoDownload Source Code

Getting Started

To build our main document there are a number of resources we need to include. The only one I am keeping within the demo folder is styles.css which creates the basic page layout. To get support for the slider widgets we need a copy of the jQuery library, the jQuery UI library, and the jQuery UI CSS all hosted by Google. You may obviously download a local copy if you would rather host these on your own website.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Range Slider with jQuery UI - Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <link rel="stylesheet" type="text/css" media="all" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css">
  <link rel="stylesheet" type="text/css" media="all" href="http://fonts.googleapis.com/css?family=Acme">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>

The actual JavaScript call to generate a slider is very simple. I will be creating two sliders within the main body section. The first only uses a single slider control, while the second will use two sliders in a range setting. All of the values can be obtained through jQuery callbacks and even setup into a hidden HTML input field to process within a backend form.

Inner Page HTML

First we need to create a container for the original slider, along with the number counter. Here is what the top of my body HTML content looks like:

  <div id="defaultval">
	Slider Value: <span id="currentval">500</span>
  </div>
  
  <div id="defaultslide"></div>
  
  <br>

#defaultslider is a container which will hold the sliding input element. This means you can directly manipulate the width and height of the object to fit into any portion of your layout. Additionally you can overwrite the default jQuery UI stylesheet effects to customize this to your own liking. jQuery UI Themeroller is an excellent web application which can aid in this process.

  <h2>Ranged Slider</h2>
  <div id="rangedval">
	Range Value: <span id="rangeval">90 - 290</span>
  </div>
  
  <div id="rangeslider"></div>

The latter portion of our page includes a very similar batch of HTML. The value container now uses an ID #rangeval and it has a value of two numbers separated by a dash. JavaScript string manipulation also makes it easy to turn this into an array, or break the numbers down into two distinct input fields.

Custom CSS Effects

My document itself does not have very much CSS which is worth looking into. There are some more unique properties and resets added into the document, but nothing exceptional to help with range sliders. There have been a lot of questions related to theming jQuery UI sliders. Throughout Google you can find a lot of helpful resources.

One great example to share is customizing the internal slider scrollbar color which can be accomplished with rudimentary CSS. It always relates to targeting internal classes within the jQuery UI CSS library. The basic code looks something like this:

div.ui-slider-range.ui-widget-header {
    background: #0000ff;
}

If you want to see more customized examples then I would recommend Codepen. Developers use this as a testing ground for new ideas and there are some unbelievable examples. Possibly my absolute favorite is this UI volume slider which makes use of custom CSS and background images to duplicate the interface of an audio sliding bar.

img

To offer just one more CSS design I would recommend jQuery UI Slider Pips which is a free open source project on Github. You can view a live demo to see how all the various slider inputs look and feel on the page. It is a lot more difficult to customize an HTML5 slider, and so with a little effort you can make a beautiful jQuery UI slider which also adapts gracefully in many web browsers.

Adding the jQuery Code

Finally our last step is to run the .slider() function attached onto each main div element. There are only two on the page but they both require slight adjustments to the default parameter settings. These codes are found at the bottom of my HTML file wrapped inside <script></script> tags. Here is the entire code block:

$(function(){
  $('#defaultslide').slider({ 
    max: 1000,
    min: 0,
    value: 500,
    slide: function(e,ui) {
      $('#currentval').html(ui.value);
    }
  });
  
  $('#rangeslider').slider({
    range: true,
    min: 0,
    max: 1000,
    values: [ 90, 290 ],
    slide: function( event, ui ) {
      $('#rangeval').html(ui.values[0]+" - "+ui.values[1]);
    }
  });
});

The max and min value parameters are easy to figure out. Also the default value will be where the slider places the scrubber button right after the page loads. Notice these values match the current number values found in my HTML. Within the slide parameter we are calling a function which will auto-update every time the user performs a new slide.

These functions will re-update the inner HTML contents inside each counter to represent the new slider value. But if you need these to be passed into a form you could make alternative functions which update an input value using the jQuery .attr() method.

jquery ui sliders inputs form

Live DemoDownload Source Code

Closing

Although my example is fairly basic it does introduce how you can build forms around these slider elements. jQuery is a supported library with many older legacy browsers, and it does provide excellent support in many ways HTML5 hasn’t quite nailed down. Feel free to download a copy of my source code and see if you can implement these sliders into your own projects. Also if you have thoughts or questions you can share with us in the discussion area below.


Advertise here with BSA

April 30 2013

13:30

Finger Tips: 3 Quick Ways to Retrofit a Site for Touchscreen Use

The future is now. Market-analysis firm IDC predicts that sales of tablet computers will exceed their desktop counterparts this year, which means that those of us not designing with touchscreens in mind are falling behind. Fortunately, it’s not too late. By addressing some key areas of our site, the team at Cars.com has improved the mobile experience of our site in a short amount of time during our ongoing redesign.

It’s no secret that responsive design helps us develop a single site to serve smartphones, tablets, and desktop displays equally well. But the thinking that goes into a good responsive design? That takes time. How might designers go about making a site tablet-friendly right away?

This is exactly the problem we currently face at Cars.com. While my team is busy considering all of the elements that make up our site (content first, kids!) and how they might be handled in a responsive manner, we’ve wanted to make some quick changes that might immediately impact visitors.

People visit Cars.com to find vehicles for sale, read editorial content, and browse consumer reviews. With these things in mind, we’ve prioritized our short-term changes by focusing on three, key areas: content, layout, and forms.

Content

As Elaine McVicar recently reminded us: when it comes to touchscreen interfaces, content is navigation. This has serious implications for Cars.com – specifically, our photo galleries and content-promoting carousels. Fortunately, mobile luminary Brad Frost has a fantastic article weighing in on this particular element.

Our takeaways? We need to make sure our carousels are swipeable, as swipe gestures allow touch-based users to more-intuitively move through the panels. Next, when it comes to galleries with thumbnail strips, we need to ensure people can swipe through thumbnails. We can’t – or, rather, shouldn’t – exclusively rely on previous and next arrows.

The examples below show what a difference these considerations can make:

The main content carousel on the BBC homepage does not recognize swipe gestures. You have to tap the right or left arrows to navigate through the content or let it play like a slideshow.

The carousel on the Cars.com homepage has a much larger area for tablet users to interact with than the one on the BBC homepage.

While accounting for large swaths of our content (and navigation), we found that we also needed to pay attention to the way in which that content presents itself. This meant considering layout.

Layout

Fingers are horribly inaccurate as pointing devices. As a consequence, Apple, Google, and Microsoft all provide guidelines for the proper sizing of tap targets. But because pixel and point sizes are variable (a topic beyond the scope of this article), Steven Hoober suggests that physical sizes be used when thinking about mobile layout.

The team at Cars.com has taken this to heart – I personally decided to keep a ruler at my desk. This allows me to measure distances right on the glass and, aside from testing with real people, provides a great way to get a feel for whether tap targets are too small or too close to one another.

Compare the left-hand navigation in the examples below from Macy’s and smart. Which would you rather use?

Macy’s faceted browsing has tap targets that are too small and too close together for tablet users to navigate easily without first zooming in. This is common in eCommerce websites in which the design predates the proliferation of tablets.

smart’s navigation design includes larger tap targets and better spacing between the targets.

Having considered both content and layout, in general, we figured: what’s next?

Forms. That’s what.

Forms

Forms do the “heavy lifting” on Cars.com. They’re one of the main ways users tell us what they want. And let’s face it: while forms can be difficult to use on desktop computers, they pose an even bigger problem on mobile devices with their small, virtual keyboards.

When it comes to forms on mobile, otherwise simple changes can go a long way towards improving usability. Luke Wroblewski’s best practices ring true:

  • Use the fewest number of form fields necessary to achieve your business goal.
  • Reduce the number of fields that require typing. If there is another way to get the information other than the keyboard, use it. I call this mindset “more tap, less type”.
  • Use native device capabilities. The GPS, compass, accelerometer, camera, address book, and native social networking apps can all provide data so people don’t have to enter it manually.
  • Let people type whatever they want. Allow people to enter values like phone numbers with various special characters even if you’re just going strip them out afterward.
  • Whenever possible, retain form contents in error states. Don’t make people retype their whole email address on a virtual keyboard because they forgot the period.

Simply by redesigning our forms against these guidelines, we increased their overall utility. What’s more, redesigning our forms also gave us a chance to reconsider our form aesthetics.

Layout

As with our content, the larger our forms’ inputs, the easier they are to navigate. Increasing the padding around form elements as well as making some of them taller and wider makes them more navigable.

Compare the previous version:

Form elements are too close for comfort on an older version of the Cars.com dealer locator form.

To the new version:

The redesigned form increases the size of the form fields and adds more spacing between elements. This reduces people’s likelihood of tapping the wrong element.

Notice the difference? Next, we use a different background or border color to indicate focus. This isn’t groundbreaking, of course, but it does provides a visual confirmation that the characters a person types will appear in the correct place – and differences like this add up.

What’s more, the CSS required to do this is super simple:

input:focus {
  background-color: #ffffe0;
  border: 1px solid #f00;
}

Finally, we looked at context-specific keyboards.

Get specific

Context-specific keyboards offer users a subset of the traditional keyboard layout to encourage completion of a specific task. For example, a “number” keyboard provides number keys (as well as commas, periods, and dollar signs) to users rather than the traditional QWERTY keyboard.

HTML5 provides an easy way to trigger the display of context-specific keyboards using the “type” attribute. Specifically:

  • <input type=”email” /> triggers a keyboard with the @ symbol and a period.
  • <input type=”number” /> triggers the keyboard with numeric digits plus characters like the dollar sign, comma, and period.
  • <input type=”url” /> triggers the keyboard with characters needed to type a URL, including a “.com” button on iOS and some Android devices.

Notice how Crate and Barrel utilizes <input type=”email” /> on their sign-in screen. When entering an email address, people are presented with an “@” key and a period key:

Crate and Barrel’s create an account screen gives people all the characters they need to type an email address on one keyboard.

We decided to make heavy use of <input type=”number” /> on Cars.com since many of our tools use ZIP code to determine the person’s general geographic location. Without utilizing this input type, people would be forced to manually switch back and forth between different keyboard layouts – alphabetical and numeric. That’s a lot of unnecessary interaction.

Oh, and one more thing: there is no negative impact to using these input types. Because older desktop browsers that don’t understand them, they default to “type=text”. Newer mobile browsers will display a more user-friendly keyboard and older desktop browsers will be unaffected.

Getting started

Improving the three, key areas of Cars.com highlighted in this article has provided our mobile-based users with a dramatically better user experience, all while affording our design and development teams more time to think through our responsive redesign.

The team at Cars.com now thinks about tablet users for every design change we make on the “traditional” site, helping to achieve a vision that’s more usable across devices. Hopefully, following a similar approach increases your team’s sensitivity to (and awareness of) the design considerations specific to touch and gesture-based interactions.

Additional resources


The post Finger Tips: 3 Quick Ways to Retrofit a Site for Touchscreen Use appeared first on UX Booth.

July 19 2012

13:00

How to Create a Multi-Step Form Using RhinoSlider

How do you feel when you see a long Sign Up form for a website or service? Generally, people get bored when the Sign Up form is too long. Ideally, you should keep the form as simple as possible with minimum fields, and if that is not possible, try using a multi-step form.

The reason why Facebook Connect and Sign In with Twitter has become so popular these days is because of their simplicity, since users can sign up just by logging into their Facebook or Twitter account.

If you are using normal Sign Up forms and still require a lot of data from your users, a multi-step form is the best solution. So the form is broken into small sections and the user only sees one section at a time. Also, multi-step forms reduces the space you need on the page.

Multi Step Form Final Layout

In this tutorial I am going to show you how to make a multi-step Sign Up form using Rhinoslider. I think you would prefer seeing the demo first.

Demo Download

Why Use RhinoSlider

In a multi-step form, once you complete the first step, the second step will be displayed and Step 1 will be hidden. Normally we use sliding effects in step transitions. So this a scenario where we can use a Slider differently from its default behavior of creating image slideshows.

There are plenty of great sliders available and no point of reinventing the wheel by creating a slider from scratch. So I chose Rhinoslider for this tutorial as it provides great effects and is very easy to customize. So let’s get started on making a multi-step form.

Introduction to Rhinoslider

Before we create the multi-step form, you should have a basic idea of how RhinoSlider works. They recommend you to generate a custom version instead of full version with all the effects. So I have downloaded the default version for our tutorial.

You can open the demo file in the browser and it will look something like the following screen.

Rhino Slider Demo

So let’s look at the demo file code first.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Multi Step Form with Rhinoslider 1.05</title>
		<link type="text/css" rel="stylesheet" href="css/rhinoslider-1.05.css" />
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="js/rhinoslider-1.05.min.js"></script>
		<script type="text/javascript" src="js/mousewheel.js"></script>
		<script type="text/javascript" src="js/easing.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$('#slider').rhinoslider();
			});
		</script>
		<style type="text/css">
			body { background-color:#000; }

			#slider {
				width:600px;
				height:250px;

				/*IE bugfix*/
				padding:0;
				margin:0;
			}

			#slider li { list-style:none; }

			#page {
				width:600px;
				margin:50px auto;
			}
		</style>
	</head>
	<body>
		<div id="page">
			<ul id="slider">
				<li><img src="img/slider/01.jpg" alt="" /></li>
				<li><img src="img/slider/02.jpg" alt="" /></li>
				<li><img src="img/slider/03.jpg" alt="" /></li>
				<li><img src="img/slider/04.jpg" alt="" /></li>
				<li><img src="img/slider/05.jpg" alt="" /></li>
			</ul>
		</div>
	</body>
</html>
  • You can see that 5 images are placed in the unordered list called #slider.
  • Once you initialize Rhinoslider with $(‘#slider’).rhinoslider() , all the images will be assigned to slider and will slide automatically.

Now we have a basic idea of how to use Rhinoslider. So Lets get started on creating multi-step form.

Creating the Multi-Step Form

We need to do some modifications in initializing the code to suit our multi-step form creation process. Consider the modified initialization code below.

                $('#slider').rhinoslider({
                    controlsPlayPause: false,
                    showControls: 'always',
                    showBullets: 'always',
		    controlsMousewheel: false,
		    prevText: 'Back',
                    slidePrevDirection: 'toRight',
		    slideNextDirection: 'toLeft'
                });
  • In the image slider top button is used to control automatic play and pause. We don’t need it in a multi step form. So we remove it by setting controlsPlayPause: false .
  • The controls and numbering on the slider are shown on hover by default. We make it permanent by setting showControls: ‘always’ and showBullets: ‘always’.
  • Slider moves on mousewheel by default. So we disable it by setting controlsMousewheel: false
  • Finally we change the previous button text to Back.

Creating Form Elements for Steps

Instead of images we want sections of form elements. So in this demo I created a simple registration form with 3 steps called PERSONAL DETAILS, ACCOUNT DETAILS and CONTACT DETAILS. Each section will have some form elements. I am going to replace the unordered list of images with my form elements as shown below.

<div id="wrapper">
        <h3>Account Registration</h3>

            <form action="" >

                <div id="slider">
                    <div class="form-step" >

                        <div class="row">
                            <div class="form-left">First Name *</div>
                            <div class="form-right"><input type="text" id="fname" name="fname" class="form-input" /></div>
                            <div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Last Name *</div>
                            <div class="form-right"><input type="text" id="lname" name="lname" class="form-input" /></div>
                            <div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Gender *</div>
                            <div class="form-right">
                                <select id="gender" name="gender">
                                    <option value="0">Select</option>
                                    <option value="M">Male</option>
                                    <option value="F">Female</option>
                                </select>
                            </div>
                            <div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Address</div>
                            <div class="form-right"><input type="text" id="address" name="address" class="form-input" /></div>
                            <div class="form-error"></div>
                        </div>

                    </div>
                    <div class="form-step" >
                        <div class="row">
                            <div class="form-left">Username *</div>
                            <div class="form-right"><input type="text" id="username" name="username" class="form-input" /></div>
<div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Password *</div>
                            <div class="form-right"><input type="text" id="pass" name="pass" class="form-input" /></div>
<div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Confirm Password *</div>
                            <div class="form-right"><input type="text" id="cpass" name="cpass" class="form-input" /></div>
<div class="form-error"></div>
                        </div>
                    </div>
                    <div class="form-step" >
                        <div class="row">
                            <div class="form-left">Email *</div>
                            <div class="form-right"><input type="text" id="email" name="email" class="form-input" /></div>
<div class="form-error"></div>
                        </div>
                        <div class="row">
                            <div class="form-left">Mobile No</div>
                            <div class="form-right"><input type="text" id="mobile" name="mobile" class="form-input" /></div>
<div class="form-error"></div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
  • First I have added a div called wrapper and a heading called Account Registration.
  • Then I have replaced the ul with a div called #slider.
  • Next I have replaced the list items of images with divs with the class “form-step”.
  • Then necessary input fields for each section are added accordingly.
  • Once the slider is initialized divs with the class containing form-step will turn into a slide.

Now copy the images in the project folder to your demo folder and include the following CSS styles in the demo file.

<style type='text/css'>
        body { background-color:#fff; }
        #wrapper{
            border: 1px solid #DCDADA;
            border-radius: 5px 5px 5px 5px;
            box-shadow: 2px 2px 2px #E1E1E1;
            background: #fff;
            width:700px;
            height:480px;
            background:#f4f4f4;

        }
        #wrapper h3{
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
            font-size:16px;
            height:60px;
            background:url(img/title.png) no-repeat left top;
            margin:0;
            padding:16px 0 0 20px;
            text-shadow: 1px 1px 2px #000;
            filter: dropshadow(color=#000, offx=1, offy=1);
            color:#fff;
        }
        #slider {

            background: #fff;
            /*IE bugfix*/
            padding:0;
            margin:0;
            width:700px;
            height:400px;

        }

        #slider li { list-style:none; }

        #page {
            width:600px;
            margin:50px auto;
        }

        #slider{
            color: #000;
            background:#f4f4f4;
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
            font-size:12px;
        }

        .form-step{

            padding:16% 3% !important;

        }

        .form-submit{
            cursor: pointer;
            display: block;
            position: absolute;
            right: 0;
            bottom: 0;
            -moz-user-select: none;
            background: none repeat scroll 0 0 #6F95DC;
            border-radius: 5px 5px 5px 5px;
            color: #FFFFFF;
            display: block;
            margin: 0 20px 20px;
            padding: 10px;
            text-align: center;
            width: 125px;
            z-index: 10;
            font-weight: bold;
            text-decoration: none;
            background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#94b9e9), to(#4870d2));
            background-image: -moz-linear-gradient(#94b9e9, #4870d2);
            background-image: -webkit-linear-gradient(#94b9e9, #4870d2);
            background-image: -o-linear-gradient(#94b9e9, #4870d2);
            filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#94b9e9, endColorstr=#4870d2)";
            -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#94b9e9, endColorstr=#4870d2)";
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

        }

        .errorDisplay{
            border:2px solid red;
        }

        .form-left{
            color: #717171;
            float: left;
            font-size: 13px;
            font-weight: bold;
            padding: 5px;
            width: 200px;
        }
        .form-right{
            float: left;
            width: 214px;
        }
        .row{
            float: left;
            margin: 5px 0;
            width: 100%;
        }
        .form-step input[type='text']{
            border: 1px solid #CFCFCF;
            border-radius: 4px 4px 4px 4px;
            height: 25px;
            padding: 3px;
            width: 200px;
        }
        select{
            border-radius: 4px;
            border: 1px solid #CFCFCF;
            -webkit-border-radius: 4px;
            -moz-border-radius: 4px;
            background: #FFF;
            padding: 2px;
            height: 30px;
            width:205px;
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
            font-size:12px;
            background:#f4f4f4;
        }

        select option{
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
            font-size:12px;
            background:#f4f4f4;
            color:#717171;
        }

        .form-error{
            color: red;
            font-size: 12px;
            padding: 8px;
        }

        .step-error{
            background:#f5715f !important;
            color:#FFF !important;
            -moz-box-shadow:1px 1px 4px #C6C4C4
                -webkit-box-shadow:1px 1px 4px #C6C4C4
                box-shadow:1px 1px 4px #C6C4C4
        }
        .step-success{
            background:#72e487 !important;
            color:#FFF !important;
            -moz-box-shadow:1px 1px 1px 4px #C6C4C4
                -webkit-box-shadow:1px 1px 1px 4px #C6C4C4
                box-shadow:1px 1px 1px 4px #C6C4C4
        }
        .bullet-desc{
            font-size: 14px;
            font-weight: bold;
        }
    </style>

Now the slider will look something like the image below:

Multi Step Form Layout 1

So let’s compare it with our final output screen.

  • Left button should be changed to Back
  • Right button should be changed to Proceed
  • Numbering menu should change to steps on the top bar

Converting Rhinoslider Icons to Buttons

First we have to make sure that we remove the default icons displayed for previous and next buttons and insert buttons for back and proceed. Open the CSS file in the Rhinoslider CSS folder and change the styles for rhino-btn as follows.

.rhino-btn {
    cursor: pointer;
    display: block;
    position: absolute;
    right: 0;
    bottom: 0;
    -moz-user-select: none;
    background: none repeat scroll 0 0 #6F95DC;
    border-radius: 5px 5px 5px 5px;
    color: #FFFFFF;
    display: block;
    margin: 0 20px 20px;
    padding: 10px;
    text-align: center;
    width: 125px;
    z-index: 10;
    font-weight: bold;
    text-decoration: none;
    background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#94b9e9), to(#4870d2));
    background-image: -moz-linear-gradient(#94b9e9, #4870d2);
    background-image: -webkit-linear-gradient(#94b9e9, #4870d2);
    background-image: -o-linear-gradient(#94b9e9, #4870d2);
    filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#94b9e9, endColorstr=#4870d2)";
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#94b9e9, endColorstr=#4870d2)";
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

Take a look at the updated form below.

Multi Step Form Layout 2

Converting Numbered Menu Into Step Menu

We need to change the CSS styles related to the numbering menu in order to get it to the top part and make custom steps instead of just numbers. So update the styles of Rhinoslider CSS file with the following code:

.rhino-bullets li a.rhino-bullet {
    display: block;
    width: 100%;
    height: 90px;
    cursor: pointer;
    background: none repeat scroll 0 0 #F8FDFF;
    border: 1px solid #EEEEEE;
    font-size: 10px;
    text-align: center;
    padding: 10px 0 5px 0;
    color: #000;
    text-decoration:none;
    -webkit-user-select:none;
    -moz-user-select:none;
    user-select:none;
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size:13px;
}
.rhino-bullets {
    position: relative;
    top: -438px;
    z-index: 10;
    background: #fff;
    padding:0;
    float:left;
}

.rhino-bullets:before, .rhino-bullets:after {
    position:absolute;
    display:block;
    left:-16px;
    content:' ';
    width:16px;
    height:26px;

}

.rhino-bullets li {
    float:left;
    display:inline;
    margin:0;
    width: 233px;
}

.rhino-bullets li a.rhino-bullet.rhino-active-bullet {
    color:#000;
    background:#fff;
    border-bottom: none;
}

Now the CSS changes are completed and our screen will look like this:

Multi Step Form Layout 3

Adding Step Descriptions

Instead of using numbers for steps we planned to use descriptive text about the step with an image. So add the following code right after the initialization part of slider.

              var info = ["PERSONAL DETAILS","ACCOUNT DETAILS","CONTACT DETAILS"];
		var images = ["personal-details-icon.png","account-details.png","contact-details.png"];

                $('.rhino-bullet').each(function(index){
                    var link_text = $(this).html();
		    var description = $("#rhino-item"+(link_text-1)).attr("data");

                    $(this).html('<p style="margin: 0pt; font-size: 13px; font-weight: bold;"><img src="./img/'+images[index]+'"></p><p class="bullet-desc">'+info[index]+'</p></a>');
                });
  • We got 2 arrays for images and descriptions. Insert the text and images in the order of your steps.
  • Each step has a class called rhino-bullet. So while looping through each step we replace the number with the image and text from the array.

Here is our form after the text and image integration.

Multi Step Form Layout 4

Adjusting Control Buttons

In the slider we saw the previous and next buttons for each slide. But for multi-step form we don’t need a previous button in first step. So let’s see how we can remove that.

              $(".rhino-prev").hide();
                $('.rhino-next').after('<a class="form-submit" href="javascript:void(0);" >Proceed</a>');
                $(".rhino-next").hide();
  • When the page is loaded, active slide will always be the first section. So we hide the Back button by using $(“.rhino-prev”).hide().
  • Then before we go into the next step we need to validate the form. So we hide the default next button of Rhinoslider and insert the Proceed button as shown above.

Validating Form Steps

Generally we have to complete a step before we go to the next step in a multi-step form. In this section I’ll explain how to add validation to each step.

        $('.form-submit').live("click",function(){

                $('.form-error').html("");

                var current_tab = $('#slider').find('.rhino-active').attr("id");

                switch(current_tab){
                    case 'rhino-item0':
                        step1_validation();
                        break;
                    case 'rhino-item1':
                        step2_validation();
                        break;
                    case 'rhino-item2':
                        step3_validation();
                        break;
                }
            });

            var step1_validation = function(){

                var err = 0;

                if($('#fname').val() == ''){
                    $('#fname').parent().parent().find('.form-error').html("First Name is Required");
                    err++;
                }
                if($('#lname').val() == ''){
                    $('#lname').parent().parent().find('.form-error').html("Last Name is Required");
                    err++;
                }
                if($('#gender').val() == '0'){
                    $('#gender').parent().parent().find('.form-error').html("Please Select Gender");
                    err++;
                }
                if(err == 0){
                    $(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
                    $(".rhino-next").show();
                    $('.form-submit').hide();
                    $('.rhino-next').trigger('click');
                }else{
                    $(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
                }

            };
  • Our Proceed button has a class called form-submit. So every time we click on the proceed button the above validation function is called.
  • You can find the current tab using rhino-active class. Then based on the step you call a custom validation function.
  • I have shown the necessary validations for step 1 in the above code. Validations for the other two steps can be found in the project files.
  • If validation error is found, we display the errors in front of the field and make the highlight the step in red color by adding step-error class to active step.
  • If there are no errors, we make the step green by adding class step-success.
  • Then we hide our custom proceed button and display the default next button of Rhinoslider.
  • Then we make the next button click automatically by using $(‘.rhino-next’).trigger(‘click’) function which will move the form to the next step.

Following screens shows the form on validation errors and validation success.

Multi Step Form Layout 5

Customizing Rhinoslider Plugin

Now we are coming to the final part of the tutorial. We need to make some changes to the default Rhinoslider functionality to get things done as we need. You can click on the steps and move to the other steps in the demo we have now. So let’s see how we can disable it.

Disable Click Event for Steps

Open the rhinoslider-1.05.min.js file in the js folder and comment the following code section which provides the clickable functionality.

vars.buttons.bullets.click(function(){
        var itemID=$(this).attr('id').replace('-bullet','');
        var $next=vars.container.find('#'+itemID);
        var curID=parseInt(vars.navigation.find('.'+vars.prefix+'active-bullet').attr('id').replace('-bullet','').replace(vars.prefix+'item',''),10);
        var nextID=parseInt(itemID.replace(vars.prefix+'item',''),10);
        if(curID&lt;nextID){
            next($slider,settings,$next);
        }else if(curID&gt;nextID){
            prev($slider,settings,$next);
        }else{
            return false;
        }
        if(settings.autoPlay){
            pause();
        }
    });

Customizing Previous Button Functionality

I have made the previous button hidden in the initial step. Now we need to show it in other steps. So let’s customize the Rhinoslider previous button functionality to meet our requirements.

            vars.buttons.prev.click(function(){

                prev($slider,settings);
                if(settings.autoPlay){
                    pause();
                }
            });

The code above shows the default functionality of previous function. So let’s change it to the following.

          vars.buttons.prev.click(function(){
                    $(".rhino-next").hide();
                    $('.form-submit').show();
                    $('.form-submit').html("Proceed");

                    if(($slider.find('.rhino-active').index()) != 0){

                        prev($slider,settings);
                    }
                    if($slider.find('.rhino-active').index() == 1){
                        $(".rhino-prev").hide();
                    }

                    if(settings.autoPlay){
                        pause();
                    }
                });
  • Each time you click the previous button, by default the next button will be loaded. So we have to manually hide it and show our custom form submit button first.
  • Line $slider.find(‘.rhino-active’).index() will give you the index of the active step.
  • If step 1 becomes active, we hide the previous button. Otherwise we call the default previous button functionality by calling prev($slider,settings) .

Customizing Next Button Functionality

Also we need to customize the Rhinoslider next button functionality to meet our requirements. Let’s see how it works.

       vars.buttons.next.click(function(){
            next($slider,settings);
            if(settings.autoPlay){
                pause();
            }
        });

Above code shows the default functionality of previous function. So let’s change it to the following.

           vars.buttons.next.click(function(){
                    $(".rhino-next").hide();
                    $('.form-submit').show();
                    $(".rhino-prev").show();

                    if($slider.find('.rhino-active').index() != ($slider.find('.rhino-item').length -1)){
                        next($slider,settings);
                    }
                    if($slider.find('.rhino-active').index() == ($slider.find('.rhino-item').length -2)){
                        $('.form-submit').html("Submit");

                    }

                    if(settings.autoPlay){
                        pause();
                    }
                });
  • We need to hide the next button and display our custom form submit button on each next button click as we did earlier with previous button.
  • Also we need to show the previous button(Back button).
  • Then we display Submit as the button text if the form is on the final step.
  • If the active step is not the final one, we need to call next($slider,settings) to slide to next step.

We have completed the multi-step form creation process using Rhinoslider. Now you should have something similar to the provided demo. I suggest you download Rhinoslider and follow the tutorial steps to create the form instead of just looking at the project files. Finally compare your version with the demo version and make the necessary changes.

Customizing Multi-Step Form

Now we have a 3 step form. Its easy to add or remove steps according to your needs. Use the following guidelines for customizations.

  • Add or remove step descriptions from info array.
  • Add or remove step images from images array.
  • Add or remove validation functions for steps.
  • Adjust the width of rhino-bullets li class to match your needs.

Conclusion

It will take you around 2 hours to get used to Rhinoslider and create this Multi-Step form. But I think it’s worth doing it since you will have a form which can be used any time you require a multi-step form. You can add or remove steps as you wish.

In real-life projects you will not have the time to do everything from scratch. So tools such as this are useful to learn as you might need to customize existing plugins.

Some people like to do things from scratch, some like to just copy and paste the code and some like to learn the code before using it in projects. Let me know your preferences in the comments section since I am going to use your suggestions for my future tutorials.

June 26 2012

13:30

Who killed the inactive button state?

In December of 1972, distraction killed 101 people. A flight crew became so absorbed with changing a lightbulb that they didn’t notice no one was flying the plane, not even the autopilot. The crew ignored multiple warnings including a 0.5 second buzz, an amber warning indicator and the beeping of the radio altimeter, all of which indicated that their plane was precipitously falling from the sky. Warning messages could not overcome their distraction.

Inactive button states – often a stand-in for “noisy” error messages – are just as bad. As Donald Norman once wrote “the best way [to] prevent user error is to make sure that the user cannot make errors in the first place or that the effects are easily reversible.” Inactive states and error messages are our tools of the trade to that end, but both have their shortcomings. Each disrupts the user and has the capability to break their flow. Online, where distraction is high (and time and attention are scarce) interfaces that lack inactive states can help designers minimize errors with less interruption.

Going grey

Everyone who’s used a computer long enough is familiar an error message, but what exactly is an inactive state? Simply, graphical user interfaces (GUIs) are composed of widgets, many of which can be enabled or disabled at any given moment. Disabled, “inactive” widgets are often presented in a lighter color or visually obscured in some other way.

Inactive states are vestiges of software rather than effective interface elements in their own right. The typical greyed-out menu item, for example, is as old as the desktop metaphor itself:

Photo of a legacy Apple Operating System

Is this useful information?

Inactive states seem harmless, but they pose a(n often infuriating) problem to users who can’t readily figure out why they’re presented the way they are. Inactive elements cannot “speak” for themselves and can therefore never explain why they’re inactive. This introduces a real potential for confusion into our designs.

Fortunately for the denizens of the web, though, inactive interface elements have become increasingly less common. This probably something to do with the proliferation of modal interface design.

Mommy, where do modes come from?

A mode is a change in the method of operation of a device or piece of software. Modes and inactive states are related because designs that incorporate inactive states are perceptually “less” modal.

Consider Apple’s Activity Monitor, which displays inactive buttons when no process is currently selected:

You can probably guess what this application looks like when you select a process. Activity Monitor’s two modes are communicated by way of its button states. In direct contrast to this is Dropbox’s interface. Dropbox eliminates inactive states altogether, instead opting to display file-specific buttons directly next to the currently selected file.

When the user de-selects the file, the options disappear:

Which interface feels more cluttered to you? More difficult? There are certain trade-offs between hiding controls and displaying inactive buttons. Personally, Dropbox’s approach feels more intuitive than Activity Monitor’s because of the use of progressive disclosure.

Back in 2000, user interface pioneer Jef Raskin suggested that “[modes] are a significant source of errors, confusion, unnecessary restrictions and complexity in interfaces.” Modal windows are the most common place we find modes on the web today. They’re hard to miss because they inactivate and grey-out the entire web page or application. This design paradigm is intrusive and it often fails to explain (there’s that pattern again) to users why they cannot access the rest of the interface.

As a consequence, modern websites have begun to substitute overlays or dialog-like windows that don’t obscure the content underneath. Dropbox’s sign-in dialog is a good example:

Alternate approaches

A toggle switch makes it easy to understand that a particular item is unavailable, but it still doesn’t help the user know why.

Apple’s latest operating system, iOS, has led the way in eliminating inactive buttons. Given the fact that iOS apps are confined to a single window and that they lack menu-bars, the OS is almost designed to eliminate them. When inactive elements are required, though, Apple recommends using a built-in switch that combines the grey inactive desktop metaphor with the physical metaphor of a toggle switch.

Always active buttons

The web of the mid-90s had a love affair with inactive submit buttons. Greyed out on page load, they would immediately become active once the user had filled in all required form fields. More recently, though, designers have opted for alternate solutions.

If you go to Google’s iconic search page and click “I’m feeling lucky” before you’ve entered anything in the search box, you’re likely in for a surprise. Instead of an error message or an inactive state Google’s presents you with gallery of homepage doodles:

Over on Twitter’s homepage page things are even more interesting. Click Twitter’s sign in button without entering anything into the form, and you are taken to the login page. Smart. The login page’s sign in button lacks an inactive state. It simply does nothing if you try to submit a blank form.

Twitter’s sign up form behaves a bit differently. If you try to submit Twitter’s sign-up form without filling in any fields you get three error messages in red near the email, password and username fields. Rather than becoming a grey inactive button, the “create my account” button
shakes back and forth. At least in the West, the quick shake of the button is enough by itself to clearly communicate “no.”

Communicating an inactive state with a gesture

A subtle art

Buttons miming human gestures might seem odd, but it’s increasingly par for the course. Dan Eden has put together a demo page with all the different ways CSS3 can be used to enable designers to communicate to users with gestures rather than words.

Finally, some designers are going as far as providing additional information within their inactive buttons. For example, Google Chrome displays broken plugin icons over content rendered inactive by missing or disabled plugins. These icons don’t just communicate that something is inactive, they attempt to explain why.

Communicating an inactive state with a shape

Although user experience design plays a crucial role in making online commerce efficient, rarely does a mistake within a web interface have life or death consequences. There are certainly lots of ways for designers to deal with errors. As Norman wrote in n for “noisy” error messages – are just as bad. As Donald Norman once The Design of Everyday Things: “The critical thing is to approach the topic as a cooperative endeavor between person and machine…with misconceptions on either side.”

Go ahead and experiment with eliminating redundant error messages and inactive states. Let your users explore, skip ahead and break things. Just always remember to include an “undo!”


The post Who killed the inactive button state? appeared first on UX Booth.

November 08 2011

14:24

An Extensive Guide To Web Form Usability





 



 


Contrary to what you may read, peppering your form with nice buttons, color and typography and plenty of jQuery plugins will not make it usable. Indeed, in doing so, you would be addressing (in an unstructured way) only one third of what constitutes form usability.

In this article, we’ll provide practical guidelines that you can easily follow. These guidelines have been crafted from usability testing, field testing, website tracking, eye tracking, Web analytics and actual complaints made to customer support personnel by disgruntled users.

Why Web Form Usability Is Important

The ISO 9241 standard defines website usability as the “effectiveness, efficiency and satisfaction with which specified users achieve specified goals in particular environments.” When using a website, users have a particular goal. If designed well, the website will meet that goal and align it with the goals of the organization behind the website. Standing between the user’s goal and the organization’s goals is very often a form, because, despite the advances in human-computer interaction, forms remain the predominant form of interaction for users on the Web. In fact, forms are often considered to be the last and most important stage of the journey to the completion of goals.

Let’s clarify this last point by discussing the three main uses of forms. As Luke Wroblewski states in his book Web Form Design: Filling in the Blanks, every form exists for one of three main reasons: commerce, community or productivity. The following table translates each of these reasons into the user and business objectives that lie behind them:

Webform Uses

Uses of forms, based on Luke Wroblewski’s Web Form Design: Filling in the Blanks.

Thus, the relationship between forms and usability have two aspects:

  1. Forms can make a website usable or unusable, because they stand in the way of the user achieving their goal;
  2. Forms need to be usable in order to help the user achieve that goal.

This post will focus on the second point, because a usable form will naturally contribute to the overall usability of the website, hence the first aspect.

The Six Components Of Web Forms

Web forms are a necessity and often a pain point for both designers and users. Over time, users have formed expectations of how a form should look and behave. They typically expect Web forms to have the following six components:

  1. Labels These tell users what the corresponding input fields mean.
  2. Input Fields Input fields enable users to provide feedback. They include text fields, password fields, check boxes, radio buttons, sliders and more.
  3. Actions These are links or buttons that, when pressed by the user, perform an action, such as submitting the form.
  4. Help This provides assistance on how to fill out the form.
  5. Messages Messages give feedback to the user based on their input. They can be positive (such as indicating that the form was submitted successfully) or negative (“The user name you have selected is already taken”).
  6. Validation These measures ensure that the data submitted by the user conforms to acceptable parameters.

Skype’s registration form contains all six components.

Tackling Usability Via Three Aspects Of Forms

Despite differences in layout, functionality and purpose, all forms have three main aspects, as noted by Caroline Jarrett and Gerry Gaffney in their book Forms That Work: Designing Web Forms for Usability:

  1. Relationship Forms establish a relationship between the user and the organization.
  2. Conversation They establish a dialogue between the user and the organization.
  3. Appearance By the way they look, they establish a relationship and a conversation.

For a form to be usable, all three aspects need to be tackled. Let’s look at each aspect in turn to figure out how to make a form truly usable, along with practical guidelines that you can easily follow.

Aspect 1: The Relationship

“No man is an island,” the 17th-century English poet, satirist, lawyer and priest John Donne once said. Indeed, human beings thrive on relationships, be they amorous, friendly, professional or business. A form is a means to establish or enhance a relationship between the user and the organization. When done badly, it can pre-empt or terminate such a relationship.

With this in mind, a number of principles emerge:

  • Relationships are based on trust, so establishing trust in your form is critical. This can be achieved through the logo, imagery, color, typography and wording. The user will feel at ease knowing that the form comes from a sincere organization.
  • Every relationship has a goal, be it love and happiness in a romantic relationship or financial gain in a business relationship. Ask yourself, what is the goal of your form?
  • Base the name of the form on its purpose. That name will inform users what the form is about and why they should fill it in.
  • Just as in a relationship, getting to know the other person is essential. Get to know your users and always consider whether the questions you’re asking are appropriate and, if so, whether they are timely. This will instill a natural flow to your form.
  • Knowing your users will also help you choose appropriate language and remove superfluous text. And it will help you craft an interface that balances your needs and the user’s.
  • Do not ask questions beyond the scope of the form. In a relationship, you would become distrustful of someone who asked questions that were out of place. The same thing happens online. Consult with relevant stakeholders to see what information really is required.
  • Sudden changes in behavior or appearance will make users edgy. Likewise, never introduce sudden changes between forms or between steps in a form.

Debenhams login webform

Know your users. Make it easy for registered users to log in and for new users to register. Debenhams makes this distinction barely noticeable.

Amazon Sign in Form

Amazon, on the other hand, simplifies the process for registered and new customers.

Aspect 2: The Conversation

A form is a conversation. And like a conversation, it represents two-way communication between two parties, in this case, the user and the organization. In fact, the user has filled out the form in order to initiate communication with the organization.

For instance, with a social network, a user would fill out a registration form to inform the organization that they would like to join. In inviting their request (whether automatically or manually), the organization would ask the user a number of questions (in the form of labels), such as their first name, last name, email address and so forth. Upon acceptance (or denial), the company would inform the user of the outcome, thus completing the communication process.

Viewing forms from this perspective yields some useful guidelines:

  • As mentioned, a form is a conversation, not an interrogation. Aggressive wording in labels will make users feel edgy, and (if they do not leave) they will most likely give you the answers that you want to hear, rather than the truth.
  • Order the labels logically, reflecting the natural flow of a conversation. For example, wouldn’t it be weird to ask someone their name only after having asked a number of other questions? More involved questions should come towards the end of the form.
  • Group related information, such as personal details. The flow from one set of questions to the next will better resemble a conversation.

    Yahoo Form 

    Yahoo’s registration form effectively groups related content through purple headings and fine lines.

     

    Constant Contact Form

    While Constant Contact groups related content, it separates the groups too much, which could confuse the user.

  • As in a real conversation, each label should address one topic at a time, helping the user to respond in the corresponding input field.
  • The natural pauses in a conversation will indicate where to introduce white space, how to group labels and whether to break the form up over multiple pages.
  • In any conversation, people get distracted by background noise. So, remove clutter such as banners and unnecessary navigation that might distract users from filling out the form.

    Dropbox Form 

    Dropbox provides a fine example of what a registration form should look like. The white space is effective, and the page uncluttered.

Aspect 3: The Appearance

The appearance or user interface (UI) is central to the usability of a Web form, and there are several guidelines for this. To simplify the discussion, let’s group them into the six components presented earlier.

1. Labels

  • Individual words vs. sentences If the purpose of a label is simple to understand, such as to ask for a name or telephone number, then a word or two should suffice. But a phrase or sentence might be necessary to eliminate ambiguity.

    Amazon Registration

    Amazon’s registration form contains full sentences, whereas individual words would have sufficed.

  • Sentence case vs. title case Should it be “Name and Surname” or “Name and surname”? Sentence case is slightly easier — and thus faster — to follow grammatically than title case. One thing is for sure: never use all caps, or else the form would look unprofessional and be difficult to scan.

    Barnes and Noble Form

    See how difficult it is to quickly scan the labels in Barnes & Noble’s registration form?

  • Colons at the end of labels UI guidelines for some desktop applications and operating systems such as Windows recommend adding colons at the end of form labels. Some designers of online forms adhere to this, primarily because old screen readers mostly rely on the colon symbol to indicate a label. Modern screen readers rely on mark-up (specifically, the label tag). Otherwise, the colon is a matter of preference and neither enhances nor detracts from the form’s usability, as long as the style is consistent.
  • Alignment of labels: top vs. left vs. right Contrary to common advice, above the input field is not always the most usable location for a label. It’s ideal if you want users to fill in the form as fast as possible. But there are times when you’ll want to deliberately slow them down, so that they notice and read the labels attentively. Also, keeping a long form to a single column and making users scroll down the page is better than breaking it up into columns in an attempt to keep everything “above the fold.” Each style of alignment has its advantages and disadvantages:

    Table webform alignment

    *Times retrieved from “Label Placement in Forms” by Matteo Penzo.

    Makeup Geek

    Forms should never consist of more than one column. Notice how easy it is to ignore the column on the right here on Makeup Geek (not to mention the note about “Required fields” at the bottom).

2. Input Fields

  • Type of input field Provide the appropriate type of input field based on what is being requested. Each type of input field has its own characteristics, which users are accustomed to. For instance, use radio buttons if only one option of several is permitted, and check boxes if multiple choices are allowed.
  • Customizing input fields Do not invent new types of input fields. This was common in the early days of Flash websites, and it seems to be making a comeback; I have seen some odd input fields implemented with jQuery. Simple is often the most useful. Keep input fields as close to their unaltered HTML rendering as possible.

    Bit Solutions Form

    Altering the interface of input fields will confuse users.

  • Restricting the format of input fields If you need to restrict the format of data inputted by users, then at least do so in a way that won’t irritate users. For example, instead of displaying MM/DD/YYYY next to a text field for a date, consider using three drop-down fields or, better yet, a calendar control.
  • Mandatory vs. optional fields Clearly distinguish which input fields cannot be left blank by the user. The convention is to use an asterisk (*). Any symbol will do, as long as a legend is visible to indicate what it means (even if it’s an asterisk).

3. Actions

  • Primary vs. secondary actions Primary actions are links and buttons in a form that perform essential “final” functionality, such as “Save” and “Submit.” Secondary actions, such as “Back” and “Cancel,” enable users to retract data that they have entered. If clicked by mistake, secondary actions typically have undesired consequences, so use only primary actions where possible. If you must include secondary actions, give them less visual weight than primary actions.

    Not clearly distinguishing between primary and secondary actions can easily lead to failure. The above action buttons are found at the end of a lengthy form for enrolling in St. Louis Community College. Just imagine pressing the “Reset Form” button by accident.

  • Naming conventions Avoid generic words such as “Submit” for actions, because they give the impression that the form itself is generic. Descriptive words and phrases, such as “Join LinkedIn,” are preferred.

    Coca-Cola Form

    Although Coca-Cola correctly gives more importance to the primary action button, it settles for the generic word “Submit.” “Register with us” would have been more helpful.

4. Help

  • Text to accompany forms Your should never have to explain to users how to fill out a form. If it does not look like a form or it’s too complicated to fill out, then redesigning it is your only option. Accompanying text should be used only where needed, such as to explain why credit card data is being requested or how a birth date will be used or to link to the “Terms and conditions.” Such text tends to be ignored, so make it succinct and easy to read. As a rule of thumb, do not exceed 100 words of explanation (combined).
  • User-triggered and dynamic help Rather than include help text next to each input field, show it only where required. You could show an icon next to an input field that the user can click on when they need help for that field. Even better, show help dynamically when the user clicks into an input field to enter data. Such implementation is becoming more common and is relatively easy to implement with JavaScript libraries such as jQuery.

    Skype Form

    Skype’s registration form contains both user-triggered help (the blue box that is triggered by clicking the question mark) and dynamic help (the suggested user names).

5. Messages

  • Error message This notifies the user that an error has occurred, and it usually prevents them from proceeding further in the form. Emphasize error messages through color (typically red), familiar iconography (such as a warning sign), prominence (typically at the top of the form or beside where the error occurred), large font, or a combination of these.
  • Success message Use this to notify users that they have reached a meaningful milestone in the form. If the form is lengthy, a success message encourages the user to continue filling it out. Like error messages, success messages should be prominent. But they should not hinder the user from continuing.

6. Validation

  • Only where needed Excessive validation is as bad as its complete absence, because it will frustrate users. Restrict validation to confirming key points (such as the availability of a user name), ensuring realistic answers (such as not allowing ages above 130) and suggesting responses where the range of possible data is finite but too long to include in a drop-down menu (such as a country-code prefix).
  • Smart defaults Use smart defaults to make the user’s completion of the form faster and more accurate. For example, pre-select the user’s country based on their IP address. But use these with caution, because users tend to leave pre-selected fields as they are.

    Twitter Form

    Twitter’s registration form uses both dynamic validation (for the name, email address, password and user name) and smart defaults (“Keep me logged in”).

Conclusion The Beginning

The word “conclusion” is not right here. Let this be your starting point to take what I have written about and apply it to your own forms. The good news is that there is much more to say about all this; you can find an abundance of resources on each point made here. For starters, three books are listed below that inspired me when writing this post. As I stated at the beginning, taking shortcuts by only tweaking the UI will not make your forms more usable. What more can I say? The theory is now with you. Go get your hands dirty.

Further Reading

(al)


© Justin Mifsud for Smashing Magazine, 2011.

October 04 2011

14:13

Improve The User Experience By Tracking Errors





 



 


It’s easy to see your top-visited pages, navigation patterns and conversion metrics using visitor-tracking tools like Google Analytics. However, this data doesn’t show the roadblocks that users typically run into on your website. Tracking and optimizing error messages will help you measurably improve your website’s user experience. We’ll walk through how to add error tracking using Google Analytics, with some code snippets. Then, we’ll assemble the data and analyze it to figure out how to improve your error message drop rates.

What To Track

The most helpful errors to track are form-field errors and 404 pages. Form-field errors can be captured after the form’s validation has run; this can be client-side or server-side, as long as you can trigger a Google Analytics event when an error message appears to a user. (We’ll be using Google Analytics in this article, but you can apply these concepts to many visitor-tracking tools, such as Omniture and Performable.)

Form-Field Errors

Forms that allow users to create an account, log in or check out are the places where most visitors will hit stumbling blocks that you are not aware of. Pick pages with forms that have high exit rates or that have high total page views but low unique page views. This could indicate that users are repeatedly trying to submit the form but are encountering problems.

The easiest way to track form-field errors with Google Analytics is to track an event each time a user sees an error message. The specification for _trackEvent is:

_trackEvent(category, action, opt_label, opt_value)

If the form is for signing in and the user submits an incorrect password, I might use the following code:

<script type='text/javascript'>
  _gaq.push(['_trackEvent', 'Error', 'Sign In', 'Incorrect Password']);
</script>

If possible, store the error message’s text as a variable, and call this variable within Google Analytics’ event tracker. This way, as you change the text of the error message over time, you can measure the differences between the versions. For example, in PHP, I might write:

<?php
  $message = 'Incorrect password';
  if ($message) { ?>
  <script type='text/javascript'>
    _gaq.push(['_trackEvent', 'Error', 'Sign In', '<?php echo $message ?>']);
  </script>
<?php } ?>

If it’s possible for the user to receive more than one error message on the page at a time (for example, if they’ve missed more than one field in a form), then you might want to store all of the messages in the same event tracker. Use an array, or concatenate them into the variable that you call in your event tracker. You might see that a user has attempted to skip all of the fields in a form; this could indicate that they are testing the form to see which fields are required and which are optional. You’ll notice this if you have tracked an event that includes all missing fields in the same event. However, storing all of the messages in the same event might prevent you from tracking the effects of individual error messages over time, so begin by tracking each error message separately.

404 Pages

You might already know how many times your 404 page is being viewed, but do you know which URLs the users were trying to reach, or what websites are referring to those URLs? By adding a tracking code to your 404 pages, you can see both. The following snippet will include the URL that generated the 404 error and the URL that linked to that page:

<script type="text/javascript">
  _gaq.push(['_trackEvent', 'Error', '404', 'page: ' + document.location.pathname + document.location.search + ' ref: ' + document.referrer ]);
</script>

Google Analytics Reports

As you track errors as events using Google Analytics, you will find a list of them in your reports under “Event Tracking,” under the “Content” menu. Choose “Categories,” and then start drilling down through your error types.

You can save any of these graphs to your dashboard with the “Add to Dashboard” button at the top of each screen. I find it useful to list the top 404 errors on my dashboard, so that I can see whether anything new has popped up when I log in.

Google Analytics also lets you know of spikes in error messages. The “Intelligence” section allows you to set an alert for when a certain metric reaches a specified threshold. In my case, I want to know when the number of unique 404 errors has increased by more than 20% over the previous day.

In your custom alert, set the alert’s conditions to include “Event Action,” matching your error’s name exactly. In this case, the error name is “404.” Set it to alert you when the “Unique Events” percentage increases by more than 20% over the previous day. Be sure to check the box for the option to receive an email when this alert triggers!

Once you have captured enough data to analyze, start creating these dashboard widgets and alerts in Google Analytics, so that you can make informed decisions on how to improve your website.

How To Analyze Errors

Error messages will help you see in aggregate the most common stumbling blocks for users. Are a lot of users encountering errors with a particular text field? Perhaps the field for the expiration date of their credit card? Or for their email address? You might be surprised by what your users encounter.

Segmenting Data

If your website gets a lot of traffic, consider segmenting the user base to analyze the error messages. Look for groups of users who make up the majority of a certain kind of error event, because there may be something unique about that segment.

“New Visitors” are first-time visitors to your website. They are likely unfamiliar with the typical flow of your navigation and are brand new to your forms and so don’t know what fields are required. “Returning Visitors” will likely be familiar with your website, so they may not have a large impact on error rates (unless you’ve changed something that catches them by surprise).

To change the user segment that you’re looking at, go to your list of error events and click the drop-down menu next to “Advanced Segments.” By selecting “New Visitors” and then hitting “Apply,” the data will update to show only the errors that “New Visitors” have encountered.

Break down your data on error messages according to user segment in order to analyze the data more deeply.

Segmenting users by country can also give more context. I once wrestled with why so many users were triggering error messages for ZIP and postal codes in a form. After organizing the data by country, I saw a high number of errors from one country whose postal-code syntax I hadn’t accounted for in my form’s validation. I fixed the error and saw the error rate for ZIP and postal codes drop.

Check errors by country to see whether any patterns emerge in your error messages.

Referring sources for 404 pages is another way to examine the data. Use the “Filter Event Label” search bar to show errors whose referring source is a particular domain. Searching your own domain first is useful to see which incorrect URLs you can quickly fix on your own website.

Prioritize Issues

After segmenting the data, prioritize the errors that you want to fix. The top priority will be errors that affect a large group of people (i.e. ones that have a high number of unique events). Next, work on the errors that you know you can easily fix. You likely already know the cause of some errors (poor validation, unhelpful error message, etc.), so clean those up. For 404 errors, check which referring links come from your website, and fix those.

Examine 404 errors to see whether any particular referring links can be easily fixed.

Once you’ve cleaned up the errors that are easy to fix, track the new data for at least a week before doing another round of prioritization. Examine what has changed in the top errors and where they come from, and then research the cause of those errors.

Often, forms will need to be made more intuitive to help users avoid error messages. For example, if a lot of users are making mistakes when entering a date, then play with that field. Does your user base prefer drop-down menus for days, months and years? Do they make fewer errors if given a date picker? Are you giving them helpful examples of the syntax they need to follow? Track your changes and measure the rate of error events after each change to see what decreases user error.

Improve Your Error Messages

Improving the text, design and layout of your error messages could decrease the number of repeated errors by users. An error message might not be clear or might be hidden on the page; improve the user experience by testing changes to your error messages.

I prefer A/B testing to compare the effectiveness of error messages and their designs. On one form, I noticed that a number of users were skipping the phone-number field altogether, even though I’d indicated that it was required.

Some of the indicators of a required field that we tested.

After A/B testing different ways to indicate that the field was required and why it was required, we found that the combination of a link and a tooltip helped users recognize the need to fill in their phone number. This solution drastically decreased the rate of errors for this field.

On 404 pages, test out different content on users: link to your most popular pages; present a search form; try humorous content or Easter eggs to lighten the users’ spirits.

As you test different textual and design changes to your error messages, be sure to measure their effectiveness. Examine the following:

  • Total error events, and total events per error message;
  • Unique events per error message;
  • Exit rates on pages with forms and 404 pages.

All of these rates should drop. Ideally, your users should find the website so intuitive that your error event data will represent only those who try to “beat the system.”

Conclusion

To sum up, track error messages and 404 pages as events in Google Analytics, and analyze the top error patterns. Prioritize the causes of errors, and continue to improve your forms and 404 pages to avoid errors altogether. Lastly, test changes in the content and design of error messages to see whether they decrease repeated errors. Improving your forms, 404 pages and error messages will improve your website’s overall user experience.

Additional Resources

(al)


© Lara Swanson for Smashing Magazine, 2011.

August 23 2011

13:04

New approaches to designing log-in forms

Great read this morning over at Smashing Magazine but Luke Wroblewski exploring examples and practices of form design solutions and user experience.

06:14

Techniques for Constructing Usable Registration Forms

Advertise here with BSA


Most websites offer a way for users to sign up into their databases. This is often coupled with a username or e-mail address tied to a unique user ID number. The process of creating a user database is heavily developed and streamlined to a point. However there is still a lot of debate in the realm of registration forms and layout design.

User Signup Sheet Pen

I’m hoping to bring you some newer ideas and techniques to building usable forms. The registration process can be annoying and arduous. You won’t be able to capture all of your visitors. But to reduce the length and weight of your form will allow more freedom from your audience. Individual tweaks to your signup forms can go a long way in user experience.

Use Plenty of White Space

Padding is something you don’t hear recommended very often. But when users are trying to fill out multiple form areas, it can be annoying to keep your eyes focused in one tight area. Having all your info scrunched together seems like a good idea on paper. But generally in practice the user will have a much more difficult time comprehending the layout.

If you are using external labels off your form inputs you should also allow for the proper margins between forms. Labeling can become a gruesome mess when your forms are all close together. You should be able to skim the form from a distance and figure out which fields belong to what data. There are tons of jQuery effects you could use to enhance your form aesthetics as well.

iPhone 4 Tumblr Mobile

For example, when users tab between different fields you could highlight the selected areas. Either a border color change or even an outer glow can look very nice and draw the user’s attention. Google Chrome has already added this setting by default. Also you may consider diminishing the luminosity of your fonts within the field, so selected text becomes darker than the rest.

Offer Tooltips or Side-Notes

If you’re unfamiliar with tooltips, these are the little bubbles which pop up when hovering over a link. The text is usually set by the title attribute of the anchor HTML element. Dealing with tooltips in forms you should recognize there aren’t as many limits. You could have them appear underneath the form, or on either side. You could also change the colors and fonts and really customize them to be your own.

Whenever your user would hover or select a field you can choose to display some helpful information. As an example you could display a tip for passwords stating “password must be over 6 chars long”. If you’ve seen examples of this technique you’ll recognize to hide each tooltip when the user loses focus on each field.

Classic Digg Registration Page

If you don’t like the display style of tooltips you can adopt the functionality and port it to another view. Such as updating your label text in a new color. Or you could alternatively place hidden paragraphs next to each field and display them as your users pass through. You can see a great example in DesignShack’s Digg Sign-Up form tutorial targeting the Digg v3 layout.

Remove Extraneous Details

It can seem like fancy icons are the perfect spice to spread over your signup forms. I would have to argue this idea to a fault. With smaller icons which blend into the background you can get away with a great UI effect. These can help your visitors understand what your form is intending to do, or alternatively label each of your input fields without words.

But it is very simple to go overboard with these ideas. Too many extra buttons and icons will confuse your visitors. Remember that with plenty of space and precise labels your visitors won’t be very picky on design. It’s even a good idea to keep the amount of fields down to a minimum.

Working with Desk Clutter

I always recommend the big 4 entities – Username, E-mail address, Password and repeat password. You can cut the list down to 3 by using e-mail in place of their username. And although you could reduce to only 1 password field, it’s highly discouraged in practice. Users aren’t able to see the password they’ve entered. And with no failsafe methods they could easily misspell something and wreak havoc on the entire signup.

Utilize jQuery/Web Scripting

It can be tough to decide how you want to develop the signup interface. Straight HTML and CSS is always the safest option. They are supported in all modern browsers and don’t require very much finesse. But most of your visitors will be running browsers supporting JavaScript actions.

jQuery Scripting and Coding

The jQuery Library offers a whole slew of possibilities for opening your forms in a popup window. There are lightbox-style popups similar to Facebook messaging. Available also are modal popups and dropdown menus which originally hide your forms until the user is looking to signup. These methods will not only look fancy but will clear up room in your pages for other content. Users won’t feel pestered by a signup box but will have access at any point to register.

If you are unfamiliar with jQuery you may want to spend a bit of time researching the language. We have a great beginner’s tutorial for jQuery programming with some awesome tips and external links. Similarly the design community is very encouraging for new developers. So don’t be afraid to ask questions and Google a lot!

Design Gallery

There are so many examples of great signup forms. Great websites tend to leverage their way into the mainstream through some means. This is great for the design community, since other designers will pick up on the trends. Below is a small collection of my favorite registration forms from a couple top-quality websites.

Netlog

Signup for Netlog

43Things

Signup for 43 Things

Dropbox

Signup for Dropbox

Twitterfeed

Signup for Twitterfeed

Flow App

Signup for Flow free

Convore

Signup for Convore

The Discount Box

Signup for Discount Box

DesignFloat

Signup for DesignFloat

Rollyo

Signup for Rollyo

Big Cartel

Signup for Big Cartel

Cultured Code

Signup for Cultured Code Forums

Jolicloud

Signup for Jolicloud

Tumblr

Signup for Tumblr Account

CloudApp

Signup for CloudApp

odosketch

Signup for Odosketch

Conclusion

The registration process is an extremely private and somewhat lengthy part of the Internet. Users are adept at filling out web forms by this point. They have mostly become accustomed to the formatting from hundreds of other websites. But the design revolution is quickly changing how we process web signups.

These tips should offer a grand overview towards building usable web forms. Frequent visitors to your website are most likely interested in signing up. So it’s your job to make the registration process hassle-free and streamlined as possible. If you have similar ideas for constructing web signup forms please leave your thoughts in the comment area below.

Tags: Tips forms

August 15 2011

15:57

45 jQuery Plugins And Tutorials To Enhance Your Forms

Creating awesome and appealing forms for your website has now become easy, thanks to jQuery plugins. Here we are sharing with you a collection of some extremely useful plugins and tutorials to help you create beautiful and awesome web forms.

Web forms are the crucial element for any website as website visitors use such forms to interact with the webmaster. Therefore, keeping them neat and functional while maintaining their aesthetic appeal is important. Here is the complete list. Enjoy!

Boxy –Facebook-like dialog/overlay ( Demo | Download )
Boxy is a flexible, Facebook-style dialog box for jQuery with support for dragging and size tweening.

Screenshot

A jQuery Inline Form Validation ( Demo | Download )
When it comes to form validation, it’s hard to have a versatile solution that works with every form. Figuring out how to display errors is not a simple task. When an error needs to be displayed, the script creates a div and positions it in the top right corner of the input. This way you don’t have to worry about your HTML form structure. The rounded corner and shadow are done with CSS3 and degrade well in non compliant browsers.

Screenshot

ToChecklist plugin ( Demo | Download )
The toChecklist plugin for jQuery will give you the functionality of a SELECT box without the need to ctrl+click items to select them.

Screenshot

A Fancy Contact Form ( Demo | Download )
Providing a simple and reliable means of feedback from site visitors is a crucial part of any web presence. The most simple and common feedback channel are contact forms. In this tutorial we are going to make an AJAX contact form which leverages modern web development techniques.

Screenshot

Select Multiple Form Fields ( Demo | Download )
asmSelect is a jQuery plugin that answers some of these issues. A progressive enhancement is applied to the select multiple that makes it much easier to use. This enhancement automatically hides the original select multiple, and instead presents a regular select showing the available options, and an HTML list showing the already-selected options.

Screenshot

Creating a Digg Style Sign Up Form ( Demo | Download )
In this tutorial we are going to simulate their signup form, with unique features such as their dynamic tooltips that give you a hint on each field that is to be filled. The same approach will be adopted for displaying validation messages.

Screenshot

jQuery Show Password Plugin ( Demo | Download )
This plugin works by adding a text field that takes the value of what is typed into the password field. Then, when the link is clicked the password field is hidden and the text field is shown.

Screenshot

Create an AJAX/jQuery/PHP Contact Form ( Demo | Download )
This tutorial uses XHTML, CSS, jQuery and a little PHP to make a pop-up/modal contact form that validates whatever is entered into the form and then uses AJAX to send the form without refreshing the page.

Screenshot

LightForm ( Demo | Download )
LightForm is a free Ajax/PHP contact form. It combines FormCheck2 for fields validation and NiceForms to style text fields and textareas.

Screenshot

MeioMask ( Demo | Download )
With meioMask plugin you can create and apply maskstot text input fields.

Screenshot

LiveValidation ( Demo | Download )
LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms.

Screenshot

WordPress plugins for contact forms ( Demo | Download )
There are lots of WordPress plugins for contact forms, but wouldn’t it be nice to have more control over the markup? In this tutorial, Trevor is going to show how to use a custom page template to create a contact form in WordPress without a plugin.

Screenshot

How to Enhance Forms Using jQuery UI ( Demo | Download )
jQuery makes creating UI so much easier without compromising speed and quality. In this tutorial we are going to enhance form using jQuery UI, so let’s get started

Screenshot

Submit A Form Without Page Refresh using jQuery ( Demo | Download )
Submit a contact form that sends an email, without page refresh using jQuery, This tutorial will help you creating a form that can be submitted without page refreshing, using JQuery.

Screenshot

Timepickr ( Demo | Download )
jquery.timepickr was created in a attempt to make the process of inputing time in a form as easy and natural as possible.

Screenshot

Password Strength Indicator and Generator ( Demo | Download )
In the example about you will see two password boxes and with them you have a generate password link and an icon showing you the strength of your password.

Screenshot

JQByte StickyForms ( Demo | Download )
StickyForms is a jQuery plugin that automatically saves all form fields into cookies, and then autofills those values on any form that shares element IDs across your site.

Screenshot

File Style jQuery ( Demo | Download )
Browsers do not let you style file inputs. File Style plugin fixes this problem. It enables you to use image as browse button. You can also style filename field as normal textfield using css. It is written using JavaScript and jQuery.

Screenshot

Autocomplete ( Demo | Download )
By giving an autocompleted field focus or entering something into it, the plugin starts searching for matching entries and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

Screenshot

Emblematiq Niceforms ( Demo | Download )
You basically know a web form when you see one as they always look the same and they’ve kept this look over the years. Try as hard as you might but web forms can only change their appearance so much. Some may argue that this is a good usability feature, and I tend to agree, but there comes a time when you just need to style web forms so that they look different. How do you do that? Niceforms comes to the rescue!

Screenshot

A BETTER FORM – SPAM-LESS ROBOT-LESS FORMS ( Demo | Download )
A Better Form is a jQuery plugin I designed to help eliminate spam comments, spam emails and other automated form submissions.

Screenshot

Progress Bar ( Demo | Download )
It’s a very simple widget with a small API that exposes a limited number of properties and methods, but it can still be highly effective and is great for providing visual feedback to visitors on the percentage of a process is left before it is complete.

Screenshot

jQuery AlphaNumeric ( Demo | Download )
jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas.

Screenshot

Build An Incredible Login Form With jQuery ( Demo | Download )
In this tutorial, we’ll create a sliding panel, that slides in to reveal more content, using JQuery to animate the height of the panel. In this case, we will be creating a hypothetical login for the new tutsplus area that’s coming soon.

Screenshot

prettyCheckboxes ( Demo | Download )
This script is for people who wants to have a consistent look for checkboxes across browser or those who simply want them to look better. By using this script you wont loose any of the regular inputs usability.

Screenshot

Improved Current Field Highlighting in Forms ( Demo | Download )
In this tutorial CSS expert Chris Coyier will tell you how to improve your form usuability and enhance them visually.

Screenshot

jQuery Ajax delete ( Demo | Download )
Removing contents with Ajax is a useful tool to have in any web designers kit. Using a few lines of jQuery we can remove a div and simultaneously remove a record from the database with Ajax. In the download and demo you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment div with a slide up animation which will remove the div. click the image below to check out the demo.

Screenshot

jQuery Auto Complete ( Demo | Download )
Auto-complete takes input from the user, and tries to form a list of words that match the users input. The function attaches itself to the input field selected, and also creates the UL drop down from within so all you need is have the styles for it ready.

Screenshot

Date Picker ( Demo | Download )
Date Picker component with a lot of options and easy to fit in your web application.

Screenshot

Plugin for Password Masking ( Demo | Download )
This plugin gives users the option to see the chracters of the password the are entering, for usability purposes.

Screenshot

jQuery Form Plugin ( Demo | Download )
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.

Screenshot

Input Fields with Images ( Demo | Download )
With this plugin you can add icons or images inside of input fields to add some flair to your forms.

Screenshot

Elastic ( Demo | Download )
Elastic makes your textareas grow and shrink to fit it’s content. It was inspired by the auto growing textareas on Facebook. The major difference between Elastic and it’s competitors is it’s weight.

Screenshot

jQuery Checkbox ( Demo | Download )
This plugin allows you to style your forms checkboxes or radio buttons.

Screenshot

iPhone Style Checkboxes ( Demo | Download )
With this plugin you can enhance standard HTML checkboxes and gives them an iPhone-like styling.

Screenshot

jQuery Autosave ( Demo | Download )
Autosave is designed to save the progress of forms by saving the fields to cookies so you won’t lose anything should anything go wrong. The plug-in saves the form fields at certain intervals (the default is every 10 seconds) and whenever you leave the page.

Screenshot

AutoTab ( Demo | Download )
Autotab provides smart auto-tabbing and filtering on text fields in a form. Simply put: once you have typed the maximum number of characters in a text field, you will automatically have focus on the next defined text field. Target text fields are defined, as well as a defined previous text field.

Screenshot

Magicpreview ( Demo | Download )
Magicpreview automatically updates selected elements on a page based on form fields. Perfect for previewing forms.

Screenshot

Using form labels as text field values ( Demo | Download )
When designing you sometimes have limited space to put and display all of the form elements. Recently that happened to me and when I was trying to squeeze in a simple newsletter form to a 120px wide area (plus a limited height). I realized that some of the elements will have to go. The obvious solution was to get rid of the labels and put only the form text fields. How will the users know what are the text fields for? I will use value attributes and write the explanation in there, something like “Input your email here”. Problem solved? Not quite. Why? Because I am a web standards freak :)

Screenshot

Checking username availability with ajax using jQuery ( Demo | Download )
The time when username availability is checked after the page is normaly processed is long way behind us. Google has it, Yahoo has it and many many more sites have it, ajax username availability checker. So in this tutorial we will make an ajax username availability checker powered with jQuery.

Screenshot

jQuery Highlight plugin ( Demo | Download )
Highlight increases usability by highlighting elements as you interact with the page. Its primary use is for forms, but it can also be used for tables, lists, or any element you specify. It can also be used to toggle elements on and off, for example, table rows.

Screenshot

A Fancy AJAX Contact Form ( Demo | Download )
Ajax Fancy Captcha is a jQuery plugin that helps you protect your web pages from bots and spammers. We are introducing you to a new, intuitive way of completing “verify humanity” tasks. In order to do that you are asked to drag and drop specified item into a circle.

Screenshot

ASM Select ( Demo | Download )
A progressive enhancement to select multiple form elements. It provides a simpler alternative with lots of advantages.

Screenshot

BABYSTEPS ( Demo | Download )
BabySteps (A ‘What About Bob?’ reference) is a simple and easily configurable tool for turning long forms into broken out steps without going from page to page.

Screenshot

BS FORM ACCELERATOR ( Demo | Download )
BS Form Accelerator will be able to use Enter or Space buttons in your forms replacing the buttons such as Tab for changing focus in fields just with assigning an ID to the form.

Screenshot

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

July 19 2011

04:12

The New and Improved Way to Create Forms with HTML5

Advertise here with BSA


After 12 long years, the core language of the world wide web (HTML or Hyper Text Markup Language) is finally undergoing a major revision with the release of HTML5. Although the much anticipated version is still in beta, with no official launch date having been announced; HTML5 has web designers and programmers buzzing about its latest features.

According to the W3C, new HTML5 features are aimed at improving support for multimedia like video embedding, providing for a better user experience and an easier time for programmers. Although HTML4 has been a huge success, (some even argue the most successful markup format to ever have been released) everyone in the Internet world has been patiently waiting while browsers update with the latest major revision to the core language. As time wanes on, people are wondering, why the wait? The thing is, HTML5 is already well-supported in browsers like Safari, Chrome, FireFox, Opera, and mobile browsers. Even Internet Explorer 9 is set to support the new HTML5. The benefit of HTML5 is that it is backwards compatible – so, if your interested in updating your sites right now, you can. There are just a few browsers that are not fully compatible with HTML5 yet.

HTML5 Logo

Upgrading to HTML5 is fairly easy because it works with HTML4. In fact there’s no reason to throw out HTML4 at all, because HTML 5 is simply a bunch of new cool features that were added to the HTML4 core language. Upgrading (if you want to call it that) to HTML5 is very simple. All you have to do is change your doctype to <!DOCTYPE html>. This new update helps keep things simple; while in HTML4 there were a range of different doc types that you could use, making it a little more tricky. You can go through right now and update all of your websites, they won’t break. All HTML4 tags are 100% supported by HTML5.

HTML5 defined over a dozen new input types and new features that you can use in your forms. The new additions to HTML5 are going to make developers lives much easier.

Place Holder Text

I think this is my favorite improvement in HTML5. All developers are used to using javascript and jQuery to do a placeholder text in an input field, but in HTML5 it makes it extremely easy for developers to display a placeholder. What’s a place holder? A place holder is when text appears in the input field and when you click on the input field it disappears. You can put hints of what the user is supposed to put in the field. As an example, if you have a phone number input box you can put (XXX) XXX-XXXX as the place holder and when they click, it will disappear. I’m sure you’ve seen this around.

place holder in HTML 5

IE

FF

Safari

Chrome

Opera

iphone

Android

-

3.7+

4+

4+

11+

4+

-

AutoFocus Fields

The current way in HTML4 to do autofocus is using javascript to focus the first input field on a web form. As soon as a web page loads, the page will move the focus to the particular input field, just as the javascript does. What’s the difference? Since this is now in the HTML markup, users who have disabilities can easily disable this attribute within their browsers. Not all browsers support the autofocus feature, but the browsers that don’t will just simply ignore the attribute. If you want it to work in all browsers just add the new HTML5 autofocus attribute, then detect if the browser supports autofocus. If it does, don’t include the autofocus script, if it doesn’t then include the autofocus script.

IE

FF

Safari

Chrome

Opera

iphone

Android

-

4+

4+

3+

10+

-

-

HTML5 Defines 13 New Input Types.

Email Addresses

The first input field I will talk about is email addresses. Browsers that don’t support the new types will simply treat it as a text field. 99% of people won’t even notice the difference until they submit (this is when the form will validate). iPhone users will notice when they click in the email input box that an @ sign and a . will appear in a shorter easier keyboard. If you have an iPhone, you know what I’m talking about.

Email Addresses in HTML 5

Web Addresses

The next input field we will look at is web addresses. If someone asks for a URL, they are expecting something such as http://www.blackrhinosolutions.com. So now input type URL again allows users that have an iPhone to have an altered virtual keyboard that will allow them to easily add periods, slashes, and .com to their string in their input box. Once again, most people will not even notice the difference until they click submit (when the form validates).

Number

Next topic is numbers. The most annoying of all the values to get is numbers. You have to do a lot of juery to make sure you validate this field. HTML5 adds type number. This includes a few extra attributes (all optional):

  • Min: Specifies the minimum acceptable value for this particular input number field
  • Max: You guessed it right, the maximum acceptable value for the number field
  • Step: Starting at the min number it will than count by the number added in this attribute. The default is 1.

Number input type in HTML 5

This will allow for only numbers (most again will not notice the difference until they try to click submit and they get an error because they typed in something other than what is allowed) and will only allow the numbers 0, 2, and 4.

Numbers as a Slider

I thought this was really cool. HTML 5 allows you to use a new type called range, which will turn the input field into a slider. This is cool for when you want to have slider controls in your web form. The mark up is the same as the number type, but just substitute type=”number” for type =”range”.

Range Type in HTML 5

Date Pickers

By far the best addition is the date picker type called date and datetime (there are other additional date/time types such as time, week, month datetime-local as well). The javascript frameworks have worked this into their libraries such as jQuery UI, YIU, but it’s still annoying to just add a date picker. HTML5 defines a new native date picker control without having to include a script on the page. As of right now Opera is one of the only ones that fully supports this feature, but as the others you can do a fall back script if it’s not supported. Eventually all browsers will be up to date.

Search

HTML5 has added search as a type for input boxes. This is minor, but a cool change for some users. It simply puts rounded edges on the input box automatically and when you start to type it places a small X to the right. Not all browsers again support this.

Seach type in html5

Color

HTML5 also defined type color, which lets you pick a color and returns the hexademical value. Opera 11 is the only browser that supports this type. I don’t think most people use this type anyway, so I don’t think it’ll be a big deal.

Form Validation

Above we spoke about cool new input types like email, date, number, etc. One of the most exciting features of HTML5 is the addition of form validation. Most developers have either client side or server side script to validate a form (I do both!). As the HTML5 form validator may not be able to replace your server side validation, it sure can eventually replace your client side validation. The issue with javascript validation is that users can easily just disable javascript and get around it. Now with HTML5, you won’t have to worry about that. Below is an example from Chrome 12. All browsers and OS’s may render the error messages differently, but this is an example of what it may look like.
All errors are from HTML5, and no javascript was added.

IE

FF

Safari

Chrome

Opera

Iphone

Andriod

-

4+

5+

10+

9+

-

-

Required Fields

HTML5 form validation isn’t just limited to validating the types of fields. It also allows for a new additional markup called, required. This allows developers to verify that all the fields were filled in without having to use javascript.

Required Fields in HTML 5

Any developer knows that these updates are essential for development turnaround time and for enhanced user experience. Once all the browsers accept HTML5 the new updates to the mark up will make the new generation of websites exceed anyone’s expectations.

Well there you have it. A quick starting guide to the new updates you can find in HTML5. If you can take anything away from this article, remember that HTML5 is not something to be scared of. It’s something that will help developers and all your HTML 4 websites can be upgraded whenever you are ready!

July 07 2011

13:48

Showcase Of Effective And Creatively Designed Contact Forms

Contact Form is a way for your visitors and clients to directly communicate with you regarding their queries and suggestions. Contact Forms not only let you interact with your visitors but are the most suitable way to welcome your visitors and encourage them to use your services.

Designing a creative and inspirational Contact Form not only does persuade the visitors but also lets you build their confidence in your goods and services. Here, we are featuring a breathtaking collection of some exceptional Website Contact Forms that help you get the best idea for your contact form. Enjoy!

Born with Design

Justdot

ArtFlavours

Needle

Andrina peric

Lionways

Spray Studio

Svn2ftp

Miki Mottes

The Waiting Room

Brian Handley Design

Beakable

Stan Gursky

Ctrln

UmQuarto

Kevadamson

Digital Base

Sandalias XTR

Wing Cheng

Denise Chandler

Jason Gray Music

Heart Breaker Fashion

Bright Bulb Studio

Kari jobe

Vismaad

Who is Leon

Foto Marcol

La Masa Mimatta

Nineteen eighty four

Fundo los paltos

Indofolio

Try triangle

Five Cent Stand

Social snack

Orca Bay Sea Foods

Bert Timmermans

Edpeixoto

Bio bak

We Love icons

I love colors

Christian Sparrow

Atelierdetour

Z indexmedia

Trendy webdesign

Lunalunera festival

Red Bull Soapbox Racer

Xruiz

CTM Argentina

Qwert City

Swiths

World Arcade

Carsonified

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

June 27 2011

13:39

Useful Ideas And Guidelines For Good Web Form Design

Advertisement in Useful Ideas And Guidelines For Good Web Form Design
 in Useful Ideas And Guidelines For Good Web Form Design  in Useful Ideas And Guidelines For Good Web Form Design  in Useful Ideas And Guidelines For Good Web Form Design

The input form is an essential element of almost any website or application these days. Input is a core method of interaction, and in many cases it represents the hard conversion point between success and failure. With the amount time and effort we put into bringing users to our sign-up and contact forms, it’s surprising that we tend not to spend a proportional amount of time on the forms themselves.

A number of techniques and elements can be used in Web forms to turn them from abject failures into successful conversion points. In this article, we’ll present some interesting examples and useful guidelines for Web form design.

A Dash Of Quirkiness

Part of Web design is about communicating personality and being relatable, because people enjoy dealing with other people. One quality that almost always helps is a bit of quirkiness and fun. A small dose of friendliness and personality will make the input process a bit more enjoyable and human.

Jarad Johnson

Jarad Johnson‘s contact form has a flavor of good ol’ post card. The visual appearance of the form makes it stand out from the usual generic forms found elsewhere. A very nice touch to an often forgotten element of Web designs. By the way, the Postage for the email postal service was already paid. Good to know. Very well done.

11jarad in Useful Ideas And Guidelines For Good Web Form Design

Red Tiki

Red Tiki’s quirkiness is tied to the company’s brand and identity, but is powerful here nonetheless. From the frame motif to the wooden character peeking out, this form feels fun and approachable. Little colloquial phrases like “This lovely form” and “We’re always keen to lend an ear” are fantastic ways to make the company more relatable. The form is bursting with personality and flare, which helps the user complete the form and click the “Submit” button.

3red in Useful Ideas And Guidelines For Good Web Form Design

Applicom

Applicom’s form is a great example of how to be clean and professional without being sterile. Styling the form like a letter — with a stamp, subtle paper texture, striped edge and handwritten addressee name — may seem cliche, but it demonstrates a certain level of personality and care. Language such as the “Do: Be fine, use your real address. Don’t: Be negative, spam” may seem trivial, but it’s important. At the end of the day, it makes users feel like they are dealing with people who aren’t afraid to speak to them. Craftsmanship always indicates care and professionalism. People like that.

5applic in Useful Ideas And Guidelines For Good Web Form Design

Sophie Hardach

Sophie Hardach‘s form is another example of a post card idea implemented in a contact form. The input fields are a bit clearer than one would think, yet the “Submit”-button is a bit more difficult to find. In order to send the message, a stamp in the right upper corner needs to be dragged to the Stamp area of the form. In fact, the form is not only very original, but also accessible. Excellent work.

20sophie in Useful Ideas And Guidelines For Good Web Form Design

Two Paperdolls

Two Paperdolls has probably the busiest contact form of all the forms featured in this article. However, the form fits wonderfully to the overall design of the page which is a “We Are Hiring” page for designers with strong focus on typography. Notice the clean real-time validation for the form: the error indicator is diplayed in the right upper corner of each input field. Too bad that the navigation through form fields doesn’t work properly with “Tab”.

10twopaper in Useful Ideas And Guidelines For Good Web Form Design

Kontain

Kontain uses a different kind of a date picker for letting users pick the date for the form. The designers have arranged the dates in four rows rather than displaying them all vertically. A nice idea for reducing the horizontal scrolling for the users.

16-1kontain in Useful Ideas And Guidelines For Good Web Form Design

Wopata

Wopata‘s slider for the timeframe in their contact form is much different from the generic sliders, select-menus and radio buttons. This is a proof that filling in Web forms can be fun.

17wopata in Useful Ideas And Guidelines For Good Web Form Design

Fi

The language used on Fi is more friendly than formal. The inviting nature is reinforced by the short colloquialism for each form field that illustrates why the information is being requested. The language of labels should give off a little charm, without being insincere or overbearing. Isn’t everyone more engaged in a conversation if the other person is pleasant and approachable?

2fi in Useful Ideas And Guidelines For Good Web Form Design

egopop

egopop has a very simple, perhaps oversimplified contact form which however has a nice touch. The weird character on the right side plays wonderfully together with the other characters on the site and makes the contact form less boring than it would be otherwise. The contact form opens in a lightbox.

6egopop in Useful Ideas And Guidelines For Good Web Form Design

IdyllicCreative

Some forms are boring, while some are beautiful. IdyllicCreative‘s contact form is remarkably simple yet beautiful. Another example of a design agency which integrated a character from their work in their contact form.

8idyl in Useful Ideas And Guidelines For Good Web Form Design

Tinkering Monkey

Tinkering Monkey‘s character on their contact page is another interesting example of how the contact form page can be made a bit less boring. Notice the FAQ area on the right side of the contact form. An excellent idea for helping customers quickly find answers to their questions once they feel lost and can’t find a solution to their problem.

25tinkering in Useful Ideas And Guidelines For Good Web Form Design

Ditio

Ditio‘s designers have decided to combine their sign up form and a contact form in a hidden sidebar box, very much like it’s often done with the fixed “Give feedback” buttons on the left or right side. Once a trigger button “Inschrijven” is clicked, users can sign-up for their account and even upload a CV. Notice that there is no textarea available for lengthy details.

3ditio in Useful Ideas And Guidelines For Good Web Form Design

Treehouse Editing

Treehouse Editing’s contact form is another example of a quirky design with a clean and lean layout. When the user navigates to the page, the background changes to a spring theme, which is itself associated with making contact, thus encouraging them to fill out and send off the form. Notice that all that is necessary for initial contact fits into a couple of fields; further information can be collected in subsequent correspondence. Ask yourself whether a minimal layout would do the trick on your website as well.

4treehouse in Useful Ideas And Guidelines For Good Web Form Design

Amazee Labs

Amazee Labs doesn’t have to do much to make its form usable and inviting. The form has only a few quirks, namely the texture, the “Hi there, let’s get in touch!” line, and the “Send It!” button. It may not seem like much, but the casual language, careful color choice and overall texture help Amazee Labs instantly feel like a friendly and easygoing bunch.

6amazi in Useful Ideas And Guidelines For Good Web Form Design

Wing Cheng

The motif of Wing Cheng’s website is an open sketchbook, with most of the sections designed as sketches and thumbnail drawings. The contact form maintains this personality and coherency by following the motif. The form is simple and appropriate. The thought diagram with the email address adds visual interest. Maintaining the hand-drawn style is what brings out the quirkiness. Imagine how jarring and uninviting this form would be if it was a default HTML field set stuck on top of a beautiful paper texture.

7wing in Useful Ideas And Guidelines For Good Web Form Design

Break It Down

No one likes a humongous unending list, especially a list of elements to fill in or interact with. Just as a giant paragraph of text is daunting to the user, so is a giant block of empty fields. To coax the user to the finish line, the designer should make them feel like they are completing steps, or bite-sized chunks. Take a giant web project: trying to wrap your head around it all at once is almost impossible. But if you break it down into goals, and then stages, and then sets of tasks, it becomes much more manageable. This is what we want in a Web form, especially if you’re asking for a sizeable amount of information. Keep in mind that you can organize a form simply by sectioning off parts of it or by arranging the content into columns.

CollisonLabs

CollisonLabs‘s contact form might appear to be a bit too complicated at the first glance, but it’s quite straightforward. The left side of the contact page contains alternative contact information as well as a map which is designed with the overall design of the website in mind. On the right side, each input field is clearly represented and highlighted when the user fills out the form. Nice, clean work.

14collision in Useful Ideas And Guidelines For Good Web Form Design

Visual Republic

Visual Republic‘s choice of design for input field labels is similar to the solution by guys over the CollisonLabs. Giving the field label a solid background with an arrow to indicate where the text would need to be typed is a nice technique that could be used more often.

26visualrepublic in Useful Ideas And Guidelines For Good Web Form Design

CSS Tricks

CSS Tricks‘s comment area is a great example of a well-organized, helpful and clean comments area. Notice how the “star” image in the text area fades away as the user types in some text in the form.

22csstricks in Useful Ideas And Guidelines For Good Web Form Design

Barley’s Greenville

Barley’s Greenville‘s form for beer rating is an interesting example of how multiple sections can be combined to make the form intuitive and easy to use. Notice the arrow-like symbol between the first and the second section as well as various shades of the brown color within the form.

23barley in Useful Ideas And Guidelines For Good Web Form Design

Blue Sky Resumes

Blue Sky Resumes uses sections to make its extremely long form much more manageable. Standard headings and horizontal rules are used to divide sections. The designer was also careful to visually distinguish the different sections so that the form doesn’t look like a long list of fields.

 in Useful Ideas And Guidelines For Good Web Form Design

Validate Clearly

Users will not spend extra time making sure they have given you all of the information you need. Many designers believe that form validation detracts from the user experience, but its effects are adverse only when done poorly. When validation is simple and clear, it merely offers alerts and guidance to the user.

Make sure that you clearly mark the problem and tell the user exactly what is wrong. The fastest way to kill the user experience is with generic error alerts that mean nothing to the user. People are more than happy to quickly fix an issue if it is pointed out to them plainly.

Moody International

Moody International provides an excellent example for a contact form that nicely combines different types of contact information in one place. On the left, you’ll find a postal address along with a map, a phone number as well as the company’s email address. The right side is dedicated for more detailed inquiries and consulation requests. The form’s labels disappear once the user has provided their data. Unfortunately, the form doesn’t have an instant real-time validation and uses JavaScript pop-ups to inform the users about their input mistakes. Besides, the map on the left side could be integrated a bit better by using zoom controls as well as search functionality provided by Google Maps.

1moody in Useful Ideas And Guidelines For Good Web Form Design

El Passion

El Passion is another example of a contact form that combines various types of contact information in a very compact and meaningful way. Real-time validation in use. The map on the left side could be zoomable, though.

5elpassion in Useful Ideas And Guidelines For Good Web Form Design

Orlando Advertising

Orlando Advertising‘s form beautifully integrates its branding colors in a clean and attractive Web form. The red borders might be misunderstood and could be used to visually highlight errors in the form, but instead validation errors are displayed once the “Submit” button is clicked.

28soap in Useful Ideas And Guidelines For Good Web Form Design

Reinvigorate

There are usually two essential elements to effective form validation: identifying the specific problem, and clearly marking how and where to fix it. Reinvigorate uses an alert icon and a loud red outline to indicate the problem, and then it uses the side column to tell the user what’s wrong with the information. Moreover, the user gets a visual indication when the information is corrected. Being clear about the problem and not leaving the user in the dark make for a smooth experience.

Reinvigorate in Useful Ideas And Guidelines For Good Web Form Design

GitHub

GitHub‘s sign up form is as simple as its overall design, yet its beauty lies not in aesthetics, but in its functionality. When you enter your credit card details, GitHub automatically recognizes the credit card provider and visually highlights it in the form, thus providing instant feedback to the user. A wonderful example of invisible design.

15-1-github1 in Useful Ideas And Guidelines For Good Web Form Design

15-2-github2 in Useful Ideas And Guidelines For Good Web Form Design

Blue Sky Resumes (revisited)

I would like to point out another great part of Blue Sky Resumes’ form. The error alert is clear and specific. By specifically telling the user that their name is missing, the user is spared confusion and is able to find their bearings quickly. To reinforce this message, the name field is clearly highlighted and marked as required.

 in Useful Ideas And Guidelines For Good Web Form Design

Interactivity

A form is an interactive part of a website or application. In general, people want to interact with elements that feel alive and that follow convention. Many forms have a slight indent, creating a slight 3-D effect, whereas other forms simply show a box outline to delineate form fields. The key to any interaction is expectation and feedback. Make sure your forms react to user input, mainly by specifying the focus and hover states of input elements.

Grooveshark VIP

On Grooveshark, its styling of the focus and active element makes it clear which field is being interacted with. Besides, erors are displayed in a nice, helpful way while error messages are displayed at the top of the “window” using Ajax.

12grooveshark in Useful Ideas And Guidelines For Good Web Form Design

The design helps the user to maintain focus and to breeze through the form. It even makes it kind of fun, because the user wants to see a response when they click on or interact with an element.

Unlocking

Unlocking‘s checkout form is a nice example of how simple design can work very well with appropriate level of responsiveness. The input fields look nice, the hover state is very clear and the hints on the right side are helpful and unobtrusive. The contact form shows a subtle blue background when the user focuses on a field.
The form uses an additional color to highlight fields. As long as the interaction creates a noticeable effect, the form will be more usable.
The highlighting is not as bold as on some other sites featured above, but still effective and interactive and perhaps even more usable.

18unlocking in Useful Ideas And Guidelines For Good Web Form Design

Jason Long

Jason Long‘s form silently sits on the page, doing nothing, unless… well, unless you send it out. Jason uses an animated contact form which flips and changes as the message is being sent. An interesting, memorable tweak that makes the user experience just a tiny bit more interesting.

38-1-black in Useful Ideas And Guidelines For Good Web Form Design

38-2-black in Useful Ideas And Guidelines For Good Web Form Design

38-3-black in Useful Ideas And Guidelines For Good Web Form Design

The Finish Line

An effective Web form should get the user to cross the finish line. It might be a “Submit” button, an order confirmation button or a sign-up button. At the end of the day, the designer wants the user to hit that conversion point and be reasonably happy with their decision.

Make sure that the way of submitting the form is bold and specific. Where possible, use language like “Send email” or “Finish signing up,” so that the user understands exactly what the button will do.

Squarespace

On Squarespace, the designer has gone as far as to label the button “Finish & Create Site” and has also made note of its function just below. This page is especially effective because of the contrast: the layout is completely monochromatic, so making the button green puts more focus on completing the process.

1sqr in Useful Ideas And Guidelines For Good Web Form Design

BLITZ

BLITZ has come up with an interesting solution for their contact form. A content block appears in a lightbox and presents three different types of contact forms: inquiry about business, jus saying “Hi” and CV submission. The forms have a similar appearance but have a different structure. In all cases, the user has a checkbox for email updates at the bottom as well as postal address under the form. One confusing bit is that the form fields get a red border when you type in your data. Some users might confuse it with error notifications.

12blitz in Useful Ideas And Guidelines For Good Web Form Design

Custom Bags HQ

Custom Bags HQ has tried to combine various content blocks within one context. The “Contact” link in the upper navigation leads to a page which contains both the contact form and the “About us” information. In our opinion, “About us” doesn’t really detract from the user experience, but it doesn’t enhance it either. The link doesn’t feel right here, at least at the first glance. Interesting idea: the form contains a checkbox asking users if they are interesting in receiving an email newsletter. A smart handle to keep customers close to you and keep them informed about your updates and news in the future.

7custombag in Useful Ideas And Guidelines For Good Web Form Design

Clear Labels

Any interaction that we encourage must be as non-threatening as possible. After all, we are asking for personal information of the user. They are under no obligation to provide it. The first step to avoiding frustration and confusion is to use plain and simple language. Make it to the point and not flowery.

Foundation Six

Foundation Six’s labeling is effective because it streamlines the process and simplifies commitment for the user. The company boils each category of information down to one word. The “Submit” button is also clear and straightforward. There is no confusion in the user’s mind. Another strength here is the balance between multiple choice and fill in the blank (which we’ll get to below).

Foundationsix 01 in Useful Ideas And Guidelines For Good Web Form Design

Bärnt&Ärnst

Bärnt&Ärnst‘s designers follow their minimalistic approach to design and provide all contact information such as postal address, phone numbers, email as well as a short form for user’s convenience. Often you really don’t need to require more information than that for the initial email.

2born in Useful Ideas And Guidelines For Good Web Form Design

Zoltan Hoszu

Zoltan Hoszu‘s contact page illustrates how icons can be used effectively to indicate the purpose of input fields. The form itself is very simple and quite unspectacular, but icons as well as some subtle textures make it a bit more distinctive and interesting.

33zoltan in Useful Ideas And Guidelines For Good Web Form Design

Stuck Axiom

The labels in Stuck Axiom’s “New business” contact form are short and concise. The simple language and clear labeling make the form non-threatening and easy for the user to fill out. Contrasting with the gray of the form fields, the “Submit” button is set off and accented in red, making it clear where to click.

8struck in Useful Ideas And Guidelines For Good Web Form Design

Solid Giant

With clear labeling, not too many check box options and predefined budget ranges, Solid Giant can get back to a potential client with a precise offer. The “Submit” button is clear and straightforward, marking the end of an intuitive path through the form. All elements are described carefully, and there is no room for the user to misinterpret what information to enter where.

9solid in Useful Ideas And Guidelines For Good Web Form Design

Joey Rabbitt

Joey Rabbitt isn’t a fan of lengty emails. The message of the textarea can contain at most 500 characters. However, if the user would like to email Joey directly, he can use an email on the right side of the page. Joey also showcases the networks he is a member of as well as his current location. Notice how beautifully the content is designed by using icons and various colors of grey throughout the page.

4joey in Useful Ideas And Guidelines For Good Web Form Design

Multiple Choice Vs. Fill In The Blank

Selecting items from a list is naturally easier than filling in a blank. A blank sometimes raises more questions than it answers, especially if the labeling is not clear or there are too many empty fields. The user may be confused by the format, the type of information being requested or how exactly to answer a question. In general, a choice is better than a blank, especially with information that could be confusing, such as scope, budget, project type, etc. This is why most order forms do not require you to fill out every piece of information.

Pieoneers

Pieoneers uses the fill-in-the-blank format in the left column for generic information, with established conventions for format and type. On the right, more complicated questions are in the form of drop-down boxes, letting you choose between broad options, so that there is no confusion or hesitation.

10pie in Useful Ideas And Guidelines For Good Web Form Design

Information Highwayman

Information Highwayman cleverly combines multiple choice and fill in the blank. The empty fields are for simple bits of information specific to the user: name, email address, comment. These are all non-threatening and could not be formatted as multiple choice. Questions related to services sought and budget tend to be more complicated. Giving user some options here simplifies the process of explaining what you’re asking for.

Information-highwayman in Useful Ideas And Guidelines For Good Web Form Design

When Things Go Wrong: Facio Design

Facio Design‘s contact form is probably the most difficult contact form featured in this article, and rightly so. The choice of typeface and the font size is suboptimal as it is very difficult to read, especially on Windows. The designers have tried to mimic the appearance of a letter, but it doesn’t quite work here. A very simple, basic form would work better here. A nice example of how aesthetics can fail the functionality of the form.

37facio in Useful Ideas And Guidelines For Good Web Form Design

Conclusion

This overview covers a few simple best practices that you can apply to Web forms. Just remember to spend the extra time on your next website; many of these approaches are not hard to implement and will lead to much higher conversion rates, but they are often overlooked. We spend so much time getting people to the door that we forget to make the door as inviting and useful as the path to it.

Useful Sources

(al) (il) (vf) (sp)


© Shawn Borsky for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: forms, showcases

June 07 2011

15:38

Build a Neat HTML5 Powered Contact Form

Advertise here

In this tutorial, we are going to learn how to create a swanky HTML5 AJAX powered contact form. The form will use some of the new HTML5 input elements and attributes, and will be validated using the browser’s built-in form validation.

We will use jQuery and Modernizr to help out with the older browsers, and PHP on the server side to validate the input.


Step 1: Getting Started

To begin, we need to setup our directory and files. To get started, I highly recommend the HTML5 boilerplate. This is a really good starting point for any HTML5 project and will save you a great deal of time. For this tutorial I chose ‘BOILERPLATE CUSTOM’.

HTML5 Boilerplate

For more information on the HTML5 boilerplate check out this guide on Nettuts+.

Once downloaded and unpacked, delete everything but index.html and the css and js folders. I also added a folder called img and a PHP file called process.php. We will use the img folder for storing image assets for our form, and process.php to handle all the server-side logic for the contact form. Here is what my directory structure looks like now:

Directory Structure

That’s all we need to get started! The HTML5 boilerplate includes an awesome CSS reset with sensible defaults and includes all the JS libraries (jQuery & Modernizr) we are going to be using today. All our JS files and CSS files have been hooked up in the index file. Now, it’s time to move on to the markup.


Step 2: The Form

Open index.html, and remove everything within the #container element. We’ll put our contact form inside this div:

<div id="contact-form" class="clearfix">
    <h1>Get In Touch!</h1>
    <h2>Fill out our super swanky HTML5 contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry :) </h2>
    <ul id="errors" class="">
        <li id="info">There were some problems with your form submission:</li>
    </ul>
    <p id="success">Thanks for your message! We will get back to you ASAP!</p>
    <form method="post" action="process.php">
        <label for="name">Name: <span class="required">*</span></label>
        <input type="text" id="name" name="name" value="" placeholder="John Doe" required="required" autofocus="autofocus" />

        <label for="email">Email Address: <span class="required">*</span></label>
        <input type="email" id="email" name="email" value="" placeholder="johndoe@example.com" required="required" />

        <label for="telephone">Telephone: </label>
        <input type="tel" id="telephone" name="telephone" value="" />

        <label for="enquiry">Enquiry: </label>
        <select id="enquiry" name="enquiry">
            <option value="general">General</option>
            <option value="sales">Sales</option>
            <option value="support">Support</option>
        </select>

        <label for="message">Message: <span class="required">*</span></label>
        <textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required="required" data-minlength="20"></textarea>

        <span id="loading"></span>
        <input type="submit" value="Holla!" id="submit-button" />
        <p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
    </form>
</div>

This is all the HTML we will need for our form. Let’s look at each individual section:

ul#errors and p#success will be holders for our error and success messages. We will hide these by default with CSS, and display them with either JavaScript or PHP once the form has been submitted. For the name input, our only requirement is that it has been filled in.

In HTML5, we do this by adding the 'required' attribute. This will force the browser to check that this field has something in it before it allows the form to be submitted. The email field is similar, but as well as being required, we actually want to make sure it is an email address that was entered. To do this, we specify this input’s type as email, which is new in HTML5. Although telephone is not a required field, we are using the tel HTML5 input type for this.

Enquiry is a standard select element, and message is a typical textarea — nothing new here. To the textarea, we will set the required attribute to make sure the user enters some text.

In HTML5, there is a new attribute for textareas called maxlength. Yep, you guessed it, this lets us set a maximum number of characters we can write in the textarea. For some daft reason, the powers that be who made the HTML5 spec did not think we would need a minlength attribute (like we do now) and there is no attribute for this. So as a makeshift minlength attribute, we are going to use another new HTML5 attribute called a custom data attribute. This is basically any attribute name prefixed with the word ‘data-’. In our case we have appropriately chosen data-minlength. This lets us essentially create our own attributes.

Another thing worth noticing is that we are setting an attribute called placeholder on all of the input elements (except telephone) and the textarea. This is a new HTML5 input attribute. When the form is first displayed, the placeholder text will appear in the input, normally in a different font color. Then, when you focus the input, the placeholder text disappears. If you blur out without filling the field in, the placeholder text is put back in. This is a pretty cool effect, and can provide the user with a bit more information on what they need to do. Previously, this would have had to be done with JavaScript.

The final thing to notice is that the name input has an HTML5 attribute, called autofocus. When the page is first loaded, this input element is given focus immediately without the user having to do anything. This is also good for prompting the user to do something.

That’s all the HTML5-ness we are going to incorporate into our markup. For more detailed information on these new attributes and inputs checkout some of these links:


Step 3: Styling the Form

Here is our form, looking a little worse for wear…

Unstyled Form

It does not look too good at the moment, and it isn’t really doing our shiny new HTML5 goodness any justice, so let’s add some CSS. Open the style.css file. The file already contains some resets and defaults that will help us make our form x-browser compatible. Scroll down and look for a comment saying:

/*
    // ========================================== \\
   ||                                              ||
   ||               Your styles !                  ||
   ||                                              ||
    \\ ========================================== //
*/

Directly after it, paste in the following CSS:

#contact-form {
    background-color:#F2F7F9;
    width:465px;
    padding:20px;
    margin: 50px auto;
    border: 6px solid #8FB5C1;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
    border-radius:15px;
    position:relative;
}

#contact-form h1 {
    font-size:42px;
}

#contact-form h2 {
    margin-bottom:15px;
    font-style:italic;
    font-weight:normal;
}

#contact-form input,
#contact-form select,
#contact-form textarea,
#contact-form label {
    font-size:15px;
    margin-bottom:2px;
}

#contact-form input,
#contact-form select,
#contact-form textarea {
    width:450px;
    border: 1px solid #CEE1E8;
    margin-bottom:20px;
    padding:4px;
}

#contact-form input:focus,
#contact-form select:focus,
#contact-form textarea:focus {
    border: 1px solid #AFCDD8;
    background-color: #EBF2F4;
}

#contact-form textarea {
    height:150px;
    resize: none;
}

#contact-form label {
    display:block;
}

#contact-form .required {
    font-weight:bold;
    color:#F00;
}

#contact-form #submit-button {
    width: 100px;
    background-color:#333;
    color:#FFF;
    border:none;
    display:block;
    float:right;
    margin-bottom:0px;
    margin-right:6px;
    background-color:#8FB5C1;
    -moz-border-radius:8px;
}

#contact-form #submit-button:hover {
    background-color: #A6CFDD;
}

#contact-form #submit-button:active {
    position:relative;
    top:1px;
}

#contact-form #loading {
    width:32px;
    height:32px;
    background-image:url(../img/loading.gif);
    display:block;
    position:absolute;
    right:130px;
    bottom:16px;
    display:none;
}

#errors {
    border:solid 1px #E58E8E;
    padding:10px;
    margin:25px 0px;
    display:block;
    width:437px;
    -webkit-border-radius:8px;
    -moz-border-radius:8px;
    border-radius:8px;
    background:#FFE6E6 url(../img/cancel_48.png) no-repeat 405px center;
    display:none;
}

#errors li {
    padding:2px;
    list-style:none;
}

#errors li:before {
    content: ' - ';
}

#errors #info {
    font-weight:bold;
}

#errors #info:before {
    content: '';
}

#success {
    border:solid 1px #83D186;
    padding:25px 10px;
    margin:25px 0px;
    display:block;
    width:437px;
    -webkit-border-radius:8px;
    -moz-border-radius:8px;
    border-radius:8px;
    background:#D3EDD3 url(../img/accepted_48.png) no-repeat 405px center;
    font-weight:bold;
    display:none;
}

#errors.visible, #success.visible {
    display:block;
}

#req-field-desc {
    font-style:italic;
}

/* Remove box shadow firefox, chrome and opera put around required fields. It looks rubbish. */
input:required, textarea:required {
    -moz-box-shadow:none;
    -webkit-box-shadow:none;
    -o-box-shadow:none;
    box-shadow:none;
}

/* Normalize placeholder styles */

/* chrome, safari */
::-webkit-input-placeholder {
    color:#CCC;
    font-style:italic;
}

/* mozilla */
input:-moz-placeholder, textarea:-moz-placeholder {
    color:#CCC;
    font-style:italic;
}

/* ie (faux placeholder) */
input.placeholder-text, textarea.placeholder-text  {
    color:#CCC;
    font-style:italic;
}

If you save and reload, your page should now look like so:

Styled Form

Now that looks better! The CSS is pretty standard, but I will go over a few things that are not so obvious:

#errors li:before {
    content: ' - ';
}

This will put a dash next to our error validation messages. It’s basically replacing the bullet point in the list, I just think this looks better.

#contact-form #submit-button:active {
    position:relative;
    top:1px;
}

This will give us a nice ‘push-down’ effect when the submit button is active.

input:required, textarea:required {
    -moz-box-shadow:none;
    -webkit-box-shadow:none;
    -o-box-shadow:none;
    box-shadow:none;
}

All browsers (except IE) by default put a red box shadow around required elements. This looks a bit over the top in my opinion, so I am removing it. I have already indicated that the field is required by putting a red asterisk in the label.

Stupid looking required inputs
/* chrome, safari */
::-webkit-input-placeholder {
    color:#CCC;
    font-style:italic;
}

/* mozilla */
input:-moz-placeholder, textarea:-moz-placeholder {
    color:#CCC;
    font-style:italic;
}

/* ie (faux placeholder) */
input.placeholder-text, textarea.placeholder-text  {
    color:#CCC;
    font-style:italic;
}

This normalizes the appearance of the placeholder text on inputs and textareas. Here we are making it a light grey and italicizing it. This will give us consistency across all browsers except Opera, which does not support the styling of placeholders. IE just does not support the placeholder attribute. Fullstop. We will be using JavaScript to polyfill this. You can read more about styling HTML5 forms with CSS(2.1 + 3) here.

You will notice in the CSS that there are a few references to images. If you do not have these, simply download the source files for this tutorial and copy them over.

We’re done with the markup, and it’s looking pretty sweet. We’re going to create a PHP fallback in case the user’s browser does not support the new form input attributes (IE), or if the user has JavaScript disabled. We are going to write some JavaScript later to polyfill the features the browser lacks. But incase the user does not have a nice shiny new browser or JavaScript enabled, we still need to validate the form submission. We will do this serverside with PHP. We are also going to use it to email us the results of a valid form.


Step 4: Preparing For The Server Side Validation

Let’s dive straight in. Open up process.php and paste in the following:

<?php
if( isset($_POST) ){

    //form validation vars
    $formok = true;
    $errors = array();

    //sumbission data
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    $date = date('d/m/Y');
    $time = date('H:i:s');

    //form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $enquiry = $_POST['enquiry'];
    $message = $_POST['message'];

    //form validation to go here....

}

What we are saying here is: only execute this following code when the request method is POST. By default, if a form is posted to a PHP script, the form’s input values are stored in a super global array called $_POST. If nothing is posted, $_POST will not be an array, the if statement will equate to false and our code will not be run.

Once we have established that this is a POST request, we can start our form processing logic. The first thing we need to do is set two variables:

  • $formok: A boolean value we can check to see if the form was valid or not at the end of the script.
  • $errors: An array that we will use to store all of the problems with the form, as we are validating it.

After that, we set some general form submission data:

  • $ipaddress: User’s IP address which can be useful for blacklisting spam, cross referencing analytics data etc.
  • $date: The date the form was submitted. We use the date function to generate the date in UK format.
  • $time: The time the form was submitted. We use the date function to generate the time.

We could combine the date and time if we wanted:

$datetime = date('d/m/Y H:i:s');

I like to keep them separate so I can use them for other things, if required. The final set of variables we are setting are the values of the submitted form fields . We are accessing the $_POST array by passing in the form field name as the key to retrieve the data for each variable.


Step 5: Validating the $_POST Data

We are going to check each variable individually now to make sure their value is valid. If it’s not, we’ll set the $formok variable to false, and store an error message in the $errors array. We will start with the name field first.

//validate name is not empty
if(empty($name)){
    $formok = false;
    $errors[] = "You have not entered a name";
}

Here, we are just making sure that $name actually has a value. If it does not, it means the user did not enter a name. We are using the empty() function to check for this. The [] after $errors is a shortcut to array_push (which is used to add an item to the end of an array). Next we will validate the email address:

//validate email address is not empty
if(empty($email)){
    $formok = false;
    $errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $formok = false;
    $errors[] = "You have not entered a valid email address";
}

We are going to check to see if a valid email address was actually entered. For this task, we are going to use the filter_var() function. Finally, we’ll need to validate the message.

//validate message is not empty
if(empty($message)){
    $formok = false;
    $errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
    $formok = false;
    $errors[] = "Your message must be greater than 20 characters";
}

Yet again, we are going to check to see if a message was entered. If something was entered, we want to make sure it’s greater than 20 characters. For this, we are going to use the strlen() function.

The telephone field and the enquiry field are not required fields, so no need to validate these. You could, if you wanted, but for the purpose of this tutorial I’m not.


Step 6: What to do Next…

Once we have validated our form results, we need to decide whether to send the user an email containing the form results or not. We kept track of the validity of the form using the $formok variable. If it is still equal to true, we want to submit the form results, otherwise we don’t.

This is the logic we are going to use to send the message (paste this in after we have done our validation):

//send email if all is ok
if($formok){
    $headers = "From: info@example.com" . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    $emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
                  <p><strong>Name: </strong> {$name} </p>
                  <p><strong>Email Address: </strong> {$email} </p>
                  <p><strong>Telephone: </strong> {$telephone} </p>
                  <p><strong>Enquiry: </strong> {$enquiry} </p>
                  <p><strong>Message: </strong> {$message} </p>
                  <p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";

    mail("enquiries@example.com","New Enquiry",$emailbody,$headers);

}

To send the message, we are going to be using the mail() function. We will need to pass this function four parameters: to, subject, message and headers.

  • to: This will be the email address that you want to send the form details to.
  • subject: This will be the email’s subject.
  • message: This will be the email’s content. We are storing this in the variable $emailbody. This is a HTML string containing the results of our form. Where you see the curly braces with our variable names in them, these will be changed into the variables value when this script is run. This is called variable substitution. This sort of substitution only works if the string is encapsulated in DOUBLE quotes, not SINGLE.
  • headers: This is used to pass additional information to the email client so it knows how to interpet the email. We are storing our headers in the $headers variable and supplying extra information on who the email is from, and what type of content it contains.

Note: Remember to change the from email address in the headers and the to email address in the mail function.

This should produce a nice email like so:

Email Screenshot

If you are on a Windows server, you may need to put this line of code in (before you declare the $headers variable) to get the mail function to work:

ini_set("sendmail_from","info@example.com");

Whether the user’s form submission was valid or not, we want to return them back to the form. If the form was valid and the message was sent, we need to provide the user with the success message. If it’s not valid, we want to display the error messages stored in the $errors array as well as populate the form fields with the data that was originally sent. We will store some variables we have been using in this script in an array and send them along with the redirect back to the form.

//what we need to return back to our form
$returndata = array(
    'posted_form_data' => array(
        'name' => $name,
        'email' => $email,
        'telephone' => $telephone,
        'enquiry' => $enquiry,
        'message' => $message
    ),
    'form_ok' => $formok,
    'errors' => $errors
);

We will be storing our data in an associative array. This array has three members:

  • posted_form_data: This will be an array containing the form data that was posted to the script.
  • form_ok: We will store the $formok variable in this, and this variable will be checked back on the form page to update the user with the appropriate message.
  • errors: We will store the $errors variable in this. This variable will be used if the $formok variable is equal to false.

The final thing for us to do is to redirect the user back to the form page, along with our $returndata array. Once we are redirected back to the form page, we will lose our $returndata variable; so, to make this data persistant, we will temporarily store it in the session.

Another thing we need to bear in mind is, ultimately, if the user’s browser has JavaScript enabled, we want to submit the form via AJAX. That will mean we will want our AJAX request to be posted to the same place as the form submission when the JavaScript is disabled. Because the form would have already been validated on the client-side, it will pass through all the server-side validation, and the details will be emailed to us. If the form is not valid, it will never be submitted (as the browser validation / JavaScript will prevent it). This means that, with the AJAX request, there is no reason for us to redirect or set any session variables. In the final part of this script, we will check to see if the current request to process.php was an AJAX request or not, and if it was, set our session variables and redirect.

//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){

    //set session variables
    session_start();
    $_SESSION['cf_returndata'] = $returndata;

    //redirect back to form
    header('location: ' . $_SERVER['HTTP_REFERER']);

}

To check if this was an AJAX request, we search for the variable, $_SERVER['HTTP_X_REQUESTED_WITH'] . Like the the super global $_POST array, there is also one called $_SERVER. This array contains server and execution environment information. Refer here for more detailed info.

We then call session_start() to give us access to the session and the set the variable $_SESSION['cf_returndata'] to mirror $returndata. On the form page, we will now be able to access this variable.

To redirect back to the form, we are using the header() function. We are telling it to redirect us to the last page we came from using the variable: $_SERVER['HTTP_REFERER'].

Altogether you should have ended up with this:

<?php
if( isset($_POST) ){

    //form validation vars
    $formok = true;
    $errors = array();

    //submission data
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    $date = date('d/m/Y');
    $time = date('H:i:s');

    //form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $enquiry = $_POST['enquiry'];
    $message = $_POST['message'];

    //validate form data

    //validate name is not empty
    if(empty($name)){
        $formok = false;
        $errors[] = "You have not entered a name";
    }

    //validate email address is not empty
    if(empty($email)){
        $formok = false;
        $errors[] = "You have not entered an email address";
    //validate email address is valid
    }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $formok = false;
        $errors[] = "You have not entered a valid email address";
    }

    //validate message is not empty
    if(empty($message)){
        $formok = false;
        $errors[] = "You have not entered a message";
    }
    //validate message is greater than 20 characters
    elseif(strlen($message) < 20){
        $formok = false;
        $errors[] = "Your message must be greater than 20 characters";
    }

    //send email if all is ok
    if($formok){
        $headers = "From: info@example.com" . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        $emailbody = "<p>You have received a new message from the enquiries form on your website.</p>
                      <p><strong>Name: </strong> {$name} </p>
                      <p><strong>Email Address: </strong> {$email} </p>
                      <p><strong>Telephone: </strong> {$telephone} </p>
                      <p><strong>Enquiry: </strong> {$enquiry} </p>
                      <p><strong>Message: </strong> {$message} </p>
                      <p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";

        mail("enquiries@example.com","New Enquiry",$emailbody,$headers);

    }

    //what we need to return back to our form
    $returndata = array(
        'posted_form_data' => array(
            'name' => $name,
            'email' => $email,
            'telephone' => $telephone,
            'enquiry' => $enquiry,
            'message' => $message
        ),
        'form_ok' => $formok,
        'errors' => $errors
    );

    //if this is not an ajax request
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
        //set session variables
        session_start();
        $_SESSION['cf_returndata'] = $returndata;

        //redirect back to form
        header('location: ' . $_SERVER['HTTP_REFERER']);
    }
}

That’s all for processing our form submission — done and dusted in under 90 lines of PHP! All we need to do now is update the user and provide either a success message or an error message. You can save process.php now.


Step 7: Update the UI

Now that we have processed the form data and have been returned to the page, we need to update the user on what has happened. This means accessing the session variable we set on process.php and working out what response to give. Because this page now needs to use PHP, we are going to need to change the file extension of index.html to .php (index.html = index.php). Don’t worry, this should not break anything we have already done.

The first thing we need to do is get our variables out of the session. To do this, we need access to the session. Right at the top of the page before any markup (above doctype) paste the following code in:

<?php session_start() ?>

Starting the session before any content is sent to the browser should prevent any ‘cannot send session cookie – headers already sent by…’ errors you may receive. Below the H2 of the form add in this PHP snippet:

<?php
//init variables
$cf = array();
$sr = false;

if(isset($_SESSION['cf_returndata'])){
    $cf = $_SESSION['cf_returndata'];
    $sr = true;
}
?>

We are setting two variables to default values. More on these later… We are then checking to see if $_SESSION['cf_returndata'] is set. We then set $cf (short for contact form) to equal our session variable. This is just so we don’t have to type $_SESSION… every time we want to access this data. The last variable $sr (short of server response), is set to true. This is a variable we are going to be checking to see if we have previously posted our form. The next thing we want to do is display an error message or success at the top of the form. Replace this:

<ul id="errors" class="">
    <li id="info">There were some problems with your form submission:</li>
</ul>
<p id="success">Thanks for your message! We will get back to you ASAP!</p>

With this:

<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
    <li id="info">There were some problems with your form submission:</li>
    <?php
    if(isset($cf['errors']) && count($cf['errors']) > 0) :
        foreach($cf['errors'] as $error) :
    ?>
    <li><?php echo $error ?></li>
    <?php
        endforeach;
    endif;
    ?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>

By default, the messages do not appear at all because, in the CSS, we’ve set 'display:none‘. Inside the class attribute of the messages, we are using PHP to add a 'visible' class to them if they are to be shown. This class sets 'display' to 'block'.

<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>

We are using the ternary operator here to check that…

  • a) the server response is equal to true and
  • b) that the form was not ok
  • .

Essentially, if we have submitted the form, $sr will equal true, and if the form was invalid $cf['form_ok'] will equal false. So the class visible will be outputted, but the PHP and message will show, and vice versa for the success message. Inside the parenthesis, we are checking the values of two variables. We are checking that $sr is equal to true and (&&) $cf['fomr_ok'] is equal to false. We are using shorthand to check these values. You could also write it this way if you wanted:

<?php echo ($sr === true && $cf['form_ok'] === false) ? 'visible' : ''; ?>

Once we have decided which message to display, we need to populate the container with the relevant data. The success message does not change, so we can leave that as it is. The error message will need populating with the validation errors. To write these out, we are simply looping through our errors array stored in the session and populating a li element inside of the ul:

<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
    <li id="info">There were some problems with your form submission:</li>
    <?php
    if(isset($cf['errors']) && count($cf['errors']) > 0) :
        foreach($cf['errors'] as $error) :
    ?>
    <li><?php echo $error ?></li>
    <?php
        endforeach;
    endif;
    ?>
</ul>

We are first checking that we have our errors array in $cf and that it contains at least one error. The if and foreach statement may look a little different to how you have seen them before. This is called Alternative Syntax. We have used alternative syntax here just to make it a little more readable with it being mixed with the HTML. You can use the normal syntax though if you like, it’s down to preference.

That’s all we need for showing the user the response of the form submission. To test this out, disable JavaScript, and submit the form. Remember that the browser will validate the form as we are using the new HTML5 elements. So to be super sure my PHP is working, I’m testing in IE8. Yes, that’s right, IE does come in handy sometimes…

If you submit the invalid form, you should get this:

Error Message

And if you fill the form in correctly, you should get:

Success Message

You should also have received an email from the code we wrote earlier (if you filled the form in correctly). Now that the form is working, the last thing we need to do is populate the form fields again with the user’s data if the submission was invalid. Swap the HTML inside of the form tags for this:

<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required="required" autofocus="autofocus" />

<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe@example.com" required="required" />

<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />

<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
    <option value="General" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>General</option>
    <option value="Sales" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>Sales</option>
    <option value="Support" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>Support</option>
</select>

<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required="required" data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>

<span id="loading"></span>
<input type="submit" value="Holla!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>

The only difference here is that we are using PHP to populate the value attribute of the inputs.

<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>

Like we did with the success and error messages, we are checking to see if $sr is equal to true and $cf['form_ok'] is equal to false, and if they are, we write out the saved value in the session for this form field. This is done using the ternary operator.

On the select, we are doing the same, except, instead of writing out the saved value, we need to check each option value to see if it matches the one saved in the session. If it matches, we write out the selected attribute for that option.

Finally, one last thing we are going to do is unset this session variable after we’ve gotten our data from it. You don’t have to do this, though; it comes down to preference. By unsetting it now, when the page is refreshed via the refresh button (not form post), an error / success message will not be shown. If you did not unset it, a user could fill in the contact form, go potter about on the internet, come back to the form and the error / success message will still be shown. I don’t like this so I’m going to prevent it by putting this line of PHP just after the closing form tags:

<?php unset($_SESSION['cf_returndata']); ?>

If you submit an invalid form, you should notice now that your form input values are retained, and if you referesh the page, the message and data should be cleared. That’s it for the PHP side of things! You should have ended up with your form looking like so:

<div id="contact-form" class="clearfix">
    <h1>Get In Touch!</h1>
    <h2>Fill out our super swanky HTML5 contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry :) </h2>
    <?php
    //init variables
    $cf = array();
    $sr = false;

    if(isset($_SESSION['cf_returndata'])){
        $cf = $_SESSION['cf_returndata'];
        $sr = true;
    }
    <ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
        <li id="info">There were some problems with your form submission:</li>
        <?php
        if(isset($cf['errors']) && count($cf['errors']) > 0) :
            foreach($cf['errors'] as $error) :
        ?>
        <li><?php echo $error ?></li>
        <?php
            endforeach;
        endif;
        ?>
    </ul>
    <form method="post" action="process.php">
        <label for="name">Name: <span class="required">*</span></label>
        <input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />

        <label for="email">Email Address: <span class="required">*</span></label>
        <input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe@example.com" required />

        <label for="telephone">Telephone: </label>
        <input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />

        <label for="enquiry">Enquiry: </label>
        <select id="enquiry" name="enquiry">
            <option value="General" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>General</option>
            <option value="Sales" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>Sales</option>
            <option value="Support" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>Support</option>
        </select>

        <label for="message">Message: <span class="required">*</span></label>
        <textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>

        <span id="loading"></span>
        <input type="submit" value="Holla!" id="submit-button" />
        <p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
    </form>
    <?php unset($_SESSION['cf_returndata']); ?>
</div>

Don’t forget the session_start() right at the top of the page! We now have a fully functional contact form.

The data is validated, and, if successful, we are emailed the form results. Further, we update the UI with the results for each submission. The newer browsers will even validate the form before it is submitted using the new HTML5 input types and attributes we have used.

This is all fine and dandy, but we can take things one step further. We can use JavaScript to polyfill the features that the browser does not have (built in validation, support for HTML5 attributes etc.) . We can even use JavaScript to display our error / success messages and submit the form using AJAX.

But why do this when the form already works? Well, it’s simple. We want to provide as much consistency accross all browsers as possible, even if it is a really naff browser. Also, if we get the client’s browser to handle all of the validation work, it saves our server’s resources as we’re not posting to it when the form is not valid. These things are super browny points, and really are not that difficult to do.


Step 8: What is a Polyfill?

“A polyfill, or polyfiller, is a piece of code that provides the technology that you, the developer, expect the browser to provide natively.”

In our case we expect the browser to support the new HTML5 input types and attributes we have used. Firefox, Chrome, Opera and Safari have pretty good native support for these. IE6 – 9 has no support for them at all. Typical. To be honest, it’s quite shocking IE9 does not have support for these things, it was only just released earlier this year. Anyhow, putting IE bashing aside (I could go on forever), the first two things we are going to polyfill are the autofocus and the placeholder attribute.

We’ll be using jQuery to help us out with our JavaScript. We’ll use it primarily to handle our AJAX request, animation and DOM traversal & manipulation. You could get away with not using it, but you would have to write a significant amount of code. Its footprint isn’t too big, so I can live with the file size. I, probably like you, would rather write less code.

We’ll also be using a JavaScript library called Modernizr to help us with feature detection. This is already included as part of our HTML5 boilerplate, so we don’t have to do anything here to get Modernizr up and running!

Navigate to the js directory and crack open script.js. We don’t have to worry about hooking up this file, jQuery or Modernizr, to index.php as this was already provided for us by the HTML5 boilerplate we used. Delete everything in this file and paste in the following:

$(function(){

    //set global variables and cache DOM elements for reuse later
    var form = $('#contact-form').find('form'),
        formElements = form.find('input[type!="submit"],textarea'),
        formSubmitButton = form.find('[type="submit"]'),
        errorNotice = $('#errors'),
        successNotice = $('#success'),
        loading = $('#loading'),
        errorMessages = {
            required: ' is a required field',
            email: 'You have not entered a valid email address for the field: ',
            minlength: ' must be greater than '
        }

    //feature detection + polyfills
    formElements.each(function(){

        //do feature detection + polyfills here

    });
});

All our code is going to live inside the $(function(){ }) block. This will mean our code will be executed as soon as the page is loaded. Also any variables or functions we declare inside this block will not interfere with any other code outside. We are then caching some DOM elements, as we will be accessing these quite a bit. It’s more efficient to cache them in this way than to request them each time you want to use them. Here is a breakdown of what each variable is:

  • form: The contact form element.
  • formElements: All input elements and textareas in the form except the submit button. This will just be an array of elements.
  • formSubmitButton: The form’s submit button.
  • errorNotice: The error notice — unordered list element.
  • successNotice: The success message — paragraph element.
  • loading: The loading span element. This will display a loading gif when the form is submitted once validated.
  • errorMessages: This is an object containing some text for our error messages. These are used more than once so we are instantiating them here. You will notice some of the messages don’t read correctly. We will dynamically add to these later when we move on to validating the form.

After this, we are using a jQuery function, called each() to iterate over the formElements array. Whilst we are iterating over the form elements, we want to do our feature detection for the placeholder attribute, and if an element has this attribute but is not supported by the browser, apply our polyfill. Here is the polyfill for the placeholder attribute:

//if HTML5 input placeholder attribute is not supported
if(!Modernizr.input.placeholder){
    var placeholderText = this.getAttribute('placeholder');
    if(placeholderText){
        $(this)
            .addClass('placeholder-text')
            .val(placeholderText)
            .bind('focus',function(){
                if(this.value == placeholderText){
                    $(this)
                        .val('')
                        .removeClass('placeholder-text');
                }
            })
            .bind('blur',function(){
                if(this.value == ''){
                    $(this)
                        .val(placeholderText)
                        .addClass('placeholder-text');
                }
            });
    }
}

Here we are using Modernizr to determine if we have support for the placeholder attribute on an input. Modernizer is an object, input is a property of that object, and placeholder is a property of input (hence all the dots). This value will either be true or false. We are checking to see if it is false (the browser does not support the placeholder attribute); if so, we implement our polyfill. The first thing we do is declare a variable that will hold the placeholder text assigned to the element. Even though the browser does not support the placeholder attribute, we can still access this attribute. We use a function, called getAttribute() for this. The keyword 'this' refers to the current DOM element we are iterating over in the loop.

Once we have the placeholder text, we can do a check to ensure that it isn’t empty. This is so we only apply our polyfill to inputs that have the placeholder attribute. We are then chaining some really useful jQuery functions together to create our polyfill. Here’s a breakdown of what we are doing:

  1. We are wrapping the ‘this’ keyword in the jQuery function ( $() ) so we have access to some of jQuery’s handy DOM functions
  2. We are adding the class 'placeholder-text‘ to the element. This will make the elements placeholder text that we are going to polyfill look like the rest of the browsers. We have set a rule for this up already in the CSS.
  3. We are setting the input’s default value to the value of the placeholder attribute. This will show the placeholder text in the input field when the page has loaded.
  4. We are binding a focus event that will check if the placeholder attribute text is the same as the inputs value. If it is, then the input’s value is set to nothing, which clears the input and we remove the ‘placeholder-text‘ class so that the text is the default input styled text.
  5. We are binding a blur event that will check if the input’s value is equal to nothing. If it is, we populate the input with the placeholder text, and re-apply the ‘placeholder-text

This will make any browser that does not support the placeholder attribute act as if it does convincingly. See the image below from IE8:

Place Holder States

We’ll next polyfill the autofocus attribute. This one is dead simple:

//if HTML5 input autofocus attribute is not supported
if(!Modernizr.input.autofocus){
    if(this.getAttribute('autofocus')) this.focus();
}

We use Modernizer to determine if the autofocus attribute is supported. If not, then we check if this element has the autofocus attribute set on it, and if it does, we focus it. Simple. In any browser that does not support this attribute, this will provide a fix.

The only other things we need to polyfill are the required attribute, the email input type, and the built in form validation. We also want to add in validation for the message length, and show the error message with details of problems with the form.


Step 9: Form Validation, Polyfill Style

//to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event.
//An invalid html5 form element will not trigger a form submit.
formSubmitButton.bind('click',function(){
    var formok = true,
        errors = [];

    formElements.each(function(){

        //validate form elements here

    });

    //if form is not valid
    if(!formok){

        //show error message here

    }
    //if form is valid
    else {

        //ajax request + show success message here

    }

    return false; //this stops submission off the form and also stops browsers showing default error message
});

We are binding a click event to the form submit button (stored in the formSubmitButton variable). When this event is triggered, we will validate the form. Normally in JavaScript we would actually do this on the submit event of the form, but as the newer browsers are using their own built in validation, the form submit event is never triggered. The browser will display its own error messages, but this is highly inconsistent accross all of the browsers, and there is currently no way of styling these. Displaying our own error message will provide consistency, and also show for browsers that do not support the new validation methods. To stop the browsers showing their default error messages we return false at the end of this function. Here is a breakdown of what the variables set at the top are for:

  • formok: This will keep track of the validity of the form.
  • errors: This is an array and will hold the error messages.

It’s similar to the PHP validation we wrote earlier!

We will start inside the loop where we are going to be validating the form elements. Inside this loop, we want to start by declaring some useful variables that we will use in our validation.

var name = this.name,
    nameUC = name.ucfirst(),
    value = this.value,
    placeholderText = this.getAttribute('placeholder'),
    type = this.getAttribute('type'), //get type old school way
    isRequired = this.getAttribute('required'),
    minLength = this.getAttribute('data-minlength');
  • name: The name of the current element.
  • nameUC: The name of the current element with the first letter uppercased. ucfirst() is a custom method of the string object that we will be writing later.
  • value: The value of the current element.
  • placeholderText: The placeholder text of the current element.
  • type: The type of current element.
  • isRequired: Whether the current element has the required attribute set on it or not.
  • minLength: The data-minlength value of current element (if applicable).

Now that we have our variables set, we can start with our validation. For the elements that are using the HTML5 input types and attributes, we can use the new validation JavaScript API to check their validity.

In HTML5, form elements have a new property called validity. This is where all the validation data for this element is stored. In Firebug, this looks like so:

Firebug Screenshot

As you can see, there are numerous properties in this object which give us a bit more of a clue as to what the problem is. The values of the properties are either false or false. In this screenshot, I tried to submit the form with no name, and I logged the validity property for the name input in the console ( console.log(this.validity) ). This shows me that a value was missing (valueMissing = true).

Our code for checking the HTML5 elements:

//if HTML5 formfields are supported
if( (this.validity) && !this.validity.valid ){
    formok = false;

    //if there is a value missing
    if(this.validity.valueMissing){
        errors.push(nameUC + errorMessages.required);
    }
    //if this is an email input and it is not valid
    else if(this.validity.typeMismatch && type == 'email'){
        errors.push(errorMessages.email + nameUC);
    }

    this.focus(); //safari does not focus element an invalid element
    return false;
}

We are checking whether this form element has the validity property, and if it does, we are then checking the valid property of the validity object to see if this field is ok. If it is not valid (I’m using the shorthand, !, to check for false), we set formok to false, and perform some tests to see what the problem is.

If the value is missing (triggered by required fields), we add an error message to the errors array we set earlier. We use the push() method of the array object for this. The error message will consist of the element’s name (first letter uppercased) concatenated with the required error message that we set earlier in our script.

If this form fields value is not missing, we then want to determine if the correct data was input. The only input in our form that needs validation is the email field. With this in mind, in the elseif part of our code, we are checking if the typeMismatch property of the validity object is equal to true and if this input’s type is actually email. If so, we add the email error message to our errors array.

When the browser validates a field and is deemed invalid, it is automatically focused. Safari does not support this, so for the sake of consistency, we manually focus the input. We then return false at the end of our HTML5 input validation to break out of the loop, as we know that we have an invalid element (we don’t need to waste our time validating the rest of the elements in the form).

This will cover our HTML5 inputs nicely, but we now need to cater to the browsers which do not support the JavaScript form validation API. If the JavaScript form validation API is not supported by the browser the above code will never be exectued and skipped.

The first thing we will check for is if the field was required. Our polyfill for this will look like:

//if this is a required element
if(isRequired){
    //if HTML5 input required attribute is not supported
    if(!Modernizr.input.required){
        if(value == placeholderText){
            this.focus();
            formok = false;
            errors.push(nameUC + errorMessages.required);
            return false;
        }
    }
}

Firstly, we check if this field is a required field (dictated by the required attribute). We are then using Modernizr to check if the required attribute is supported by the browser. If not, we need to manually check the value of the element and compare it to the element’s placeholder attribute. If they are the same, then obviously this form field has not been filled out so we do four things:

  1. We focus the input (as this what the browser does when using its native validation)
  2. We set the formok variable to false, as the form is invalid
  3. We add an error message to our errors array.
  4. We return false, which breaks out of the loop, and will go straight to the next bit of the code outside of the loop.

We are next going to check if this is an email input, and, if it is, whether a valid email has been entered.

//if HTML5 input email input is not supported
if(type == 'email'){
    if(!Modernizr.inputtypes.email){
        var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if( !emailRegEx.test(value) ){
            this.focus();
            formok = false;
            errors.push(errorMessages.email + nameUC);
            return false;
        }
    }
}

It’s pretty much the same as before. We see if this is actually an email field, and then use Modernizr to check if the email input is supported. If it’s not, we write our code that checks if it is valid or not. For this polyfill, we are using regular expressions to test if the email is valid or not. We create a regular expression in the variable emailRegEx, then use the test() method of the regular expression object to test if the value of the input is valid against the regular expression.

You can learn more on using JavaScript regular expressions here.

If the email address is not valid, we do the same four things we did on the required input check.

The last thing we need to validate in our form is the message length. The required validation has already been taken care of above, so all we need to do is check the message’s length:

//check minimum lengths
if(minLength){
    if( value.length < parseInt(minLength) ){
        this.focus();
        formok = false;
        errors.push(nameUC + errorMessages.minlength + minLength + ' charcters');
        return false;
    }
}

We don't need to use Modernizr here. Instead, all we need to do is check that this element has a minimum length set, and if it does, make sure its length is greater than its set minimum length. Length is a property of all string objects in JavaScript and returns the number of characters in the string. We use parseInt() to convert minLength to an integer to compare it against value.length. minLength was retrieved from the data-minlength attribute. This is retrieved as a string, so to prevent any potential errors down the line (comparing strings to numbers etc.), we convert this to an integer.

Our polyfills and validation are now finished and sorted. You should have ended up with the following code:

//to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event.
//An invalid html5 form element will not trigger a form submit.
formSubmitButton.bind('click',function(){
    var formok = true,
        errors = [];

    formElements.each(function(){
        var name = this.name,
            nameUC = name.ucfirst(),
            value = this.value,
            placeholderText = this.getAttribute('placeholder'),
            type = this.getAttribute('type'), //get type old school way
            isRequired = this.getAttribute('required'),
            minLength = this.getAttribute('data-minlength');

        //if HTML5 formfields are supported
        if( (this.validity) && !this.validity.valid ){
            formok = false;

            //if there is a value missing
            if(this.validity.valueMissing){
                errors.push(nameUC + errorMessages.required);
            }
            //if this is an email input and it is not valid
            else if(this.validity.typeMismatch && type == 'email'){
                errors.push(errorMessages.email + nameUC);
            }

            this.focus(); //safari does not focus element an invalid element
            return false;
        }

        //if this is a required element
        if(isRequired){
            //if HTML5 input required attribute is not supported
            if(!Modernizr.input.required){
                if(value == placeholderText){
                    this.focus();
                    formok = false;
                    errors.push(nameUC + errorMessages.required);
                    return false;
                }
            }
        }

        //if HTML5 input email input is not supported
        if(type == 'email'){
            if(!Modernizr.inputtypes.email){
                var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                if( !emailRegEx.test(value) ){
                    this.focus();
                    formok = false;
                    errors.push(errorMessages.email + nameUC);
                    return false;
                }
            }
        }

        //check minimum lengths
        if(minLength){
            if( value.length < parseInt(minLength) ){
                this.focus();
                formok = false;
                errors.push(nameUC + errorMessages.minlength + minLength + ' charcters');
                return false;
            }
        }
    });

    //if form is not valid
    if(!formok){

        //show error message here

    }
    //if form is valid
    else {

        //ajax request + show success message here

    }

    return false; //this stops submission off the form and also stops browsers showing default error message
});

Awesome! We're nearly there now. At this point, all we need to do is write the code that handles the logic to check if the form is to be submitted or not. We will need to display our error messages that we have stored, and stop the form submitting if there is an error. If, on the other hand, there isn't an error, we submit the form via AJAX and reveal the success message. We also need to cover the ucfirst() function we have used to uppercase the first letter of each field name.


Step 11: Nearly There...

The first thing we are going to do is write a function for handling the messages, and also our ucfirst() function. Paste the following code outside the formSubmitButton.bind... logic we have been writing.

//other misc functions
function showNotice(type,data)
{
    if(type == 'error'){
        successNotice.hide();
        errorNotice.find("li[id!='info']").remove();
        for(x in data){
            errorNotice.append('<li>'+data[x]+'</li>');
        }
        errorNotice.show();
    }
    else {
        errorNotice.hide();
        successNotice.show();
    }
}

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

The showNotice function will take two arguments.

  • The type of message to show
  • The data to show in the message.

If the type is 'error', we hide the success message, loop through the data (which should be an array), and append the list elements to the error notices UL. We then show the error notice using the jQuery function show(). Because all of our code is contained in the same block, we have access to variables set outside this function (successNotice and errorNotice). If we want to show the success message, we simply hide the error message and display the success message.

With the ucfirst() function, I am adding this function to the prototype of the string object.

"A prototype is an object from which other objects inherit properties."

This means that all string objects will inherit our ucfirst() function. This is why, earlier, we used name.ucfirst(). name is a string, and because our method is in the prototype, it is available for us to use.

We get the first character ( charAt(0) ), make it uppercase ( toUpperCase() ), then return it with the rest of the string minus the first character ( slice(1) ). charAt, toUpperCase and slice are all methods of the string object. You can read more about the prototype object here or here.

Now that we have our miscellaneous functions sorted out, we can concentrate on the logic for the form's outcome. We are back to working inside the formSubmitButton.bind logic.

//if form is not valid
if(!formok){

    //show error message here

}
//if form is valid
else {

    //ajax request + show success message here

}

We will start with the logic if the form is not valid. The following code should be placed inside the if statement:

//animate required field notice
$('#req-field-desc')
    .stop()
    .animate({
        marginLeft: '+=' + 5
    },150,function(){
        $(this).animate({
            marginLeft: '-=' + 5
        },150);
    });

//show error message
showNotice('error',errors);

The first chunk of code simply animates the '* indicates a required field'. This is not essential; it's just a nicety that gives the user a bit more feedback -- that a problem has, in fact, occurred. We are using the jQuery function animate() to animate the margin-left CSS value of the element. After this, we are going to call our showNotice() function. We want to show the error message so we pass 'error' as the first argument, then for the data we pass it the errors array we have been storing our form validation error messages in.

If the form is valid, we need to submit it via AJAX.

loading.show();
$.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    data: form.serialize(),
    success: function(){
        showNotice('success');
        form.get(0).reset();
        loading.hide();
    }
});

Firstly, we reveal our loading gif to indicate that the form is doing something. We then use the jQuery function ajax() to submit the form to process.php. For the url and type, we are using the jQuery function attr() to get these attributes. For the data, we use the jQuery function serialize(). If the AJAX request was successful, we call our showNotice() function and pass it 'success' as the first argument. This displays our success message. The last thing we do is reset the form (clear the form fields) and hide the loading gif. All of the JavaScript is now taken care of! Congrats1 You should have ended with your script.js file looking like so:

$(function(){

    //set global variables and cache DOM elements for reuse later
    var form = $('#contact-form').find('form'),
        formElements = form.find('input[type!="submit"],textarea'),
        formSubmitButton = form.find('[type="submit"]'),
        errorNotice = $('#errors'),
        successNotice = $('#success'),
        loading = $('#loading'),
        errorMessages = {
            required: ' is a required field',
            email: 'You have not entered a valid email address for the field: ',
            minlength: ' must be greater than '
        }

    //feature detection + polyfills
    formElements.each(function(){

        //if HTML5 input placeholder attribute is not supported
        if(!Modernizr.input.placeholder){
            var placeholderText = this.getAttribute('placeholder');
            if(placeholderText){
                $(this)
                    .addClass('placeholder-text')
                    .val(placeholderText)
                    .bind('focus',function(){
                        if(this.value == placeholderText){
                            $(this)
                                .val('')
                                .removeClass('placeholder-text');
                        }
                    })
                    .bind('blur',function(){
                        if(this.value == ''){
                            $(this)
                                .val(placeholderText)
                                .addClass('placeholder-text');
                        }
                    });
            }
        }

        //if HTML5 input autofocus attribute is not supported
        if(!Modernizr.input.autofocus){
            if(this.getAttribute('autofocus')) this.focus();
        }

    });

    //to ensure compatibility with HTML5 forms, we have to validate the form on submit button click event rather than form submit event.
    //An invalid html5 form element will not trigger a form submit.
    formSubmitButton.bind('click',function(){
        var formok = true,
            errors = [];

        formElements.each(function(){
            var name = this.name,
                nameUC = name.ucfirst(),
                value = this.value,
                placeholderText = this.getAttribute('placeholder'),
                type = this.getAttribute('type'), //get type old school way
                isRequired = this.getAttribute('required'),
                minLength = this.getAttribute('data-minlength');

            //if HTML5 formfields are supported
            if( (this.validity) && !this.validity.valid ){
                formok = false;

                //if there is a value missing
                if(this.validity.valueMissing){
                    errors.push(nameUC + errorMessages.required);
                }
                //if this is an email input and it is not valid
                else if(this.validity.typeMismatch && type == 'email'){
                    errors.push(errorMessages.email + nameUC);
                }

                this.focus(); //safari does not focus element an invalid element
                return false;
            }

            //if this is a required element
            if(isRequired){
                //if HTML5 input required attribute is not supported
                if(!Modernizr.input.required){
                    if(value == placeholderText){
                        this.focus();
                        formok = false;
                        errors.push(nameUC + errorMessages.required);
                        return false;
                    }
                }
            }

            //if HTML5 input email input is not supported
            if(type == 'email'){
                if(!Modernizr.inputtypes.email){
                    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                     if( !emailRegEx.test(value) ){
                        this.focus();
                        formok = false;
                        errors.push(errorMessages.email + nameUC);
                        return false;
                    }
                }
            }

            //check minimum lengths
            if(minLength){
                if( value.length < parseInt(minLength) ){
                    this.focus();
                    formok = false;
                    errors.push(nameUC + errorMessages.minlength + minLength + ' charcters');
                    return false;
                }
            }
        });

        //if form is not valid
        if(!formok){

            //animate required field notice
            $('#req-field-desc')
                .stop()
                .animate({
                    marginLeft: '+=' + 5
                },150,function(){
                    $(this).animate({
                        marginLeft: '-=' + 5
                    },150);
                });

            //show error message
            showNotice('error',errors);

        }
        //if form is valid
        else {
        	loading.show();
            $.ajax({
                url: form.attr('action'),
                type: form.attr('method'),
                data: form.serialize(),
                success: function(){
                    showNotice('success');
                    form.get(0).reset();
                    loading.hide();
                }
            });
        }

        return false; //this stops submission off the form and also stops browsers showing default error messages

    });

    //other misc functions
    function showNotice(type,data)
    {
        if(type == 'error'){
            successNotice.hide();
            errorNotice.find("li[id!='info']").remove();
            for(x in data){
                errorNotice.append('<li>'+data[x]+'</li>');
            }
            errorNotice.show();
        }
        else {
            errorNotice.hide();
            successNotice.show();
        }
    }

    String.prototype.ucfirst = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }

});

Conclusion

Congratulations! You've made it. It's been a long ride, and we've covered a lot of ground in this tutorial.

So, where do you go from here? This could be expanded to a much larger form, and all the code you've written will still work flawlessly. You could even add in your own validation for things like the telephone input field or the maxlength attribute!

Thanks for reading, and I hope you have enjoyed this tutorial!

May 30 2011

07:00

May 05 2011

13:32

Innovative Techniques To Simplify Sign-Ups and Log-Ins

Advertisement in Innovative Techniques To Simplify Sign-Ups and Log-Ins
 in Innovative Techniques To Simplify Sign-Ups and Log-Ins  in Innovative Techniques To Simplify Sign-Ups and Log-Ins  in Innovative Techniques To Simplify Sign-Ups and Log-Ins

There are many ways to design sign-up and log-in forms. Most designers are familiar with the conventional ways. But understanding and applying a few innovative techniques could make your forms simpler and more efficient to fill out. In this article, we’d like to present a couple of new ideas that might be useful for your next designs. Please notice that before using these techniques, you should make sure that they make sense in the context in which you are going to use them. We’d love to hear about your case-studies and usability tests that affirm or dismiss the suggestions proposed below.

Simplifying Sign-Ups

The purpose of every sign-up form is for users to complete it successfully and send it in. However, if the form is long and complicated, then the user’s excitement for your website could turn to displeasure. Here are a few innovative techniques that will make your forms faster and easier to fill out.

Ask for a User Name After The User Has Signed Up

Sign-up forms typically ask users to create a name that is unique to the website. However, coming up with a unique user name that’s not taken could take trial and error and, thus, time. Instead of hassling people for a user name when they sign up, you might want to consider asking afterwards. This way, you won’t lose sign-ups from frustrated users, and you’ll prevent users from creating random and forgettable names just to satisfy the form’s requirements.

Usernameafter in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Require Users to Type Their Password Only Once

Many sign-up forms ask users to type their password in two different fields. The reason is understandable. Forms mask passwords for security reasons, so that snoopers can’t see them. And to cut down on typographical mistakes and increase the chances of correct input, two separate entries are required.

In reality, though, this allows for greater error, because it forces users to type more. They can’t see the characters they’re inputting, making it difficult to know whether they’re typing the right password each time.

Signup2 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

A more efficient approach would be to ask users to type their password in once, but then include a box they can check to unmask the password, so that they can check it. This option could reduce the number of text fields and decrease the work that users have to do to sign up.

Auto-Fill City and State Fields Based on User’s ZIP Code

If you require the user’s home address, then consider auto-filling the city and state fields based on the ZIP code. The form will be faster to fill out because users won’t have to waste time and energy manually selecting their city and state from drop-down lists.

Signup3 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Auto-Complete the Country Field

The conventional way for users to specify their country is to select it from a drop-down list. A more efficient way would be to use an auto-complete text field. Instead of making users scroll through an alphabetical list of every country in the world, the text field would allow users to select their country from a small subset of countries that match the letters they type. The user needs only to type a few letters to see their country in the menu.

Signup4 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Allow Users to Auto-Fill Their Payment Address From the Shipping Address

If a user is buying a product, they’ll have to submit payment and shipping information. Most of the time, the addresses will be the same, so let them auto-fill one from the other. You could include a link saying “Same as shipping information” in the payment section, and when clicked, it would repeat the shipping data in the payment fields.

Signup5 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Don’t Check the Newsletter Option by Default. Offer a Preview Instead

Most website owners pre-check the newsletter box, hoping to get more subscribers. Chances are, it will work. But a subscription is meaningless if the user has done so only because they have overlooked or misunderstood the option. If they’re not interested, they’ll unsubscribe sooner or later. Forcing them to subscribe won’t help you in the long run. And receiving a newsletter without having explicitly asked for it can turn users off.

A more effective approach would be to make users want to subscribe by showing them a preview or excerpt of the newsletter. This way, they’ll know what they’re missing if they don’t subscribe. You’ll also sleep well knowing that users who subscribe have done so because they’re genuinely interested in your content.

Simplify6 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Combat Spam by Hiding a Text Field With JavaScript, Instead of Using CAPTCHA

If you get a lot of spam, then putting a CAPTCHA on your form may be necessary. What’s not necessary is making the CAPTCHA an obstacle that turns users away. Traditional CAPTCHAs that ask users to retype distorted letters have been proven to hurt conversion rates. With the extra hassle they force on users, it’s no wonder.

A simpler approach that won’t lower your conversion rate is to use a hidden and required text field generated with client-side Javascript. Spambots can’t fill in the field because they can’t interact with objects in client-side JavaScript; only users can. This method is simpler and less intrusive and so will reduce spam without hurting your conversion rate. The only problem is that it relies on JavaScript to work which might be suboptimal in some cases. You could also use Honeypot Captcha approach: you can create a honeypot form field that should be left blank and then use CSS to hide it from human users, but not bots. When the form is submitted, you check to make sure the value of that form field is blank. If it isn’t, then you can safely ignore the submission because it was submitted by a spam bot.

Javascript-captcha in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Simplifying Log-Ins

The purpose of every log-in form is to get the user into their account. Some log-in forms do this better than others. Here are a few innovative techniques that will help your users log in more efficiently.

Allow Users to Log in With Their Email Address

Remembering an email address is easier than remembering a user name. User names can be unwieldy, and people remember their email address because they use email all the time. Give users the option to log in with their email address as well as a user name. The flexibility could save them the time and headache of recovering the user name if they forget it.

Email Login in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Log Users in Without Leaving the Page

Logging in is a common task, and users will want to be able to log in from anywhere on your website. So, as soon as they do it, redirect them back to the current page. This will make logging in faster and allow users to get right back to their task.

There are a couple of ways to make this happen: a drop-down box or a modal window.

The drop-down box will open without taking users off the page. It takes up only a small part of the page, making it a fast and lightweight option.

Dropdown Login in Innovative Techniques To Simplify Sign-Ups and Log-Ins

A modal window also keeps users on the current page, but it opens up at the center of the window, putting the focus entirely on the log-in form. This option gives you room to add supplemental information to the form.

Modal-login in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Auto-Focus the First Text Field

Once the user sees the log-in form, they’ll be ready to log in. Make the process more efficient by automatically focusing on the first field. This saves them the time and effort of hovering and clicking. The user can keep their hands on the keyboard and start typing away. The auto-focus should also clearly highlight the text field so that the user knows they can start typing.

Picture-1 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Allow Users to Unmask Their Password

This option is almost as useful for logging in as it is for signing up. If users can’t see the characters in the field, they could easily mistype the password. If their input is rejected, they’ll know that they mistyped something and will have to re-enter their password until they get it right.

The problem is that users don’t know which character was mistyped and so can’t fix the mistake before submitting the form on the first attempt. This creates more work than necessary and makes users slow down their typing. Avoid this by adding a checkbox that allows users to unmask their password before submitting it.

Login4 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Use a Question Mark Icon for the Password Recovery Link

Users should have no trouble finding the password recovery link on your form. Instead of using a “Forgot your password” link, consider using a simple question mark button, which won’t take up a lot of room or get lost among other links. Because the question mark is a universal symbol for help, users will not wonder where to go when they’re having password trouble.

Login5 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Make the “Submit” Button as Wide as the Text Fields

The log-in button isn’t just for taking action: it also lets users know what action they’re about to take. A small log-in button has weak affordance and can make users feel uncertain about logging in.

A wide button gives users more confidence and is hard to miss. The button’s label also becomes more visible, so that users are clearer about the action they’re taking.

Account Login in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Allow Users to Log in Via Facebook, Twitter or OpenID

Nearly everyone has a Facebook, Twitter or OpenID account, and letting them log in with it brings big benefits. They can use your website almost instantly, without having to go through the sign-up process. Also, they won’t have to manage multiple user names and passwords across different websites.

Social Logins in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Of course, you could even go further and use Facebook Connect to actually prefill data that your users might have to type; in the example below, on Friend.ly, a Facebook application, the only thing that the user needs to do before starting using the service is just click on the “Register” button. The information about the user is loaded automatically which raises a huge privacy concern. You might not want to use this approach in practice.

Facebook-vitaly2 in Innovative Techniques To Simplify Sign-Ups and Log-Ins

Conclusion

Your sign-up and log-in forms shouldn’t make the user’s life difficult. Spending time filling out a form is no one’s idea of a party. These innovative techniques will make your forms simple and efficient, so that users can sign up and log in quickly and start enjoying your content. For further ideas and examples, you might want to consider taking a look at Joshua Johnson’s article 20 Great Sign Up Form Examples to Learn From.

(vf) (ik) (al)


© Anthony T for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: Design, forms, usability, ux

April 18 2011

05:31

20 Excellent Examples of Forms in Web Design

As we can find on Wikipedia, “Form refers to the shape, visual appearance, or configuration of an object.” And here I believe that this is also the perfect explanation… forms in web design are a way to gather information, but they must also take on a “form” or an appealing visual appearance in order to be effective. So we decided to gather some fresh examples of websites that have well designed forms. From registration to contact and login forms, you will see some very inspiring examples.

EEHarbor

EEHabor offers ExpressionEngine goods, so forms are probably their expertise.
The website itself is really beautiful and clean. The register form is clean, beautiful and straight forward, it is certainly a form that will not scar you away.

forms01
forms02

Contrast

Contrast is a web apps developer. Their website is pretty unique and nice, good usage of typography, colors and shapes. The contact form is also pretty unique and fun.

forms03
forms04

SVN2FTP

SVN2FTP is a hosted source control system. The website has a nice fun approach and a beautiful texture. The contact form is also nice and different from usual.

forms05
forms06

Ally Creative

Ally Creative is a small creative company. Their website is clean and have a nice textured background, the contact form is also pretty nice.

forms07
forms08

Think Vitamin Membership

Think Vitamin is a nice place to watch videos to learn web design and development. Besides having a nice website, all their forms are beautiful and pleasant.

forms09
forms10
forms11

Scribble & Tweak

A beautiful and neat single page layout that holds a nice and easy contact form.

forms12
forms13

Barnt & Arnst

I know I already showcased this website in previous lists, but I really like its colors and simple layout. And they deserve and extra point for their super clean contact form. ;)

forms14
forms15

The Bullitt Agency

Nice website layout based on shades of black, gray and some beiges. Beautiful background images and classic contact form.

forms16
forms17

Atlason

Clean and beautiful layout with “built in” forms for FTP and email.

forms18

Major Tom

Nice image based layout with a “hidden” sign in form for clients.

forms19
forms20

Blind Pig Design

Their website is really cool. And as for the contact form, pretty classic and clean. Also loved the subject detail from the contact form – Oink!

forms21
forms22

Clyde Quay Wharf

A residential project from New Zealand with a layout based on beautiful background images and elegant type choices. The “register your interest” form is pretty clean and beautiful.

forms23
forms24

37 East

If you are thinking about doing the real African Safari, you should check out this website. The layout is based on really beautiful background images and interesting typography.

forms25
forms26

Michael Freimuth

Michael Freimuth is a art director and illustrator. His website is pretty simple and cool. The login form to browse archives is also really nice.

forms27
forms28

Social Design House

Their website has delicate colors combination and a good choice of typography. The contact form is also pretty beautiful.

forms29
forms30

Tinkering Monkey

Besides having some pretty stylish products to sell, Tinkering Monkey has a super clean layout. The contact form is also pretty neat.

forms31
forms32

Go Live!

Need a button to shout about your work? Try this! Go Live has a pretty colorful layout and their “let’s do it form” is also really nice.

forms33
forms34

Sophie Hardach

A cool single page layout for a book website. Contact form really unique.

forms35
forms36

Soapbox

Simple layout with a beautiful color scheme.

forms37
forms38

RxBalance

Beautiful watercolored layout with texture background. Delicate colors and typography. The contact form is also really elegant and simple.

forms39
forms40

Source:

The Best Designs
siteInspire
Unmatched Style

February 02 2011

05:49

Simplify Form Handling in a Big Way


Save time, reduce maintenance pains, simplify your code, and do it all while feeling like a freakin’ genius! In this tutorial, learn how to use variable variables, lookup arrays, and a bit of clever programming to simplify form handling in a big way.


Variable Variables, Methods, and Properties

Before we can get too deep into using a lookup array, it’s important to first understand the concept behind variable variables.

What Are Variable Variables?

Variable variable is a term, which describes the use of a variable to declare another variable.

In the simplest form, a variable variable might look like:

$foo = 'A value!'; // Declare an initial value
$bar = 'foo'; // Wait, what's happening?
echo $$bar; // Holy crap! That output 'A value!'

Why Should you Care?

When you look at a proof of concept like the previous example, using variable variables probably looks pretty silly and overcomplicated. However, there really are solid, practical reasons to use them in some cases.

Lookup arrays can easily simplify your code

Practical Examples

The responsible use of variable variables can drastically reduce the amount of code that needs to be repeated by, say, converting an associative array to an object with sanitized values.

Example without variable variables

$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

Example with variable variables

$comment = new stdClass(); // Create a new object

foreach( $array as $key=>$val )
{
    $comment->$key = sanitize_values($val);
}

See how much simpler that was? And you can imagine what the example without variable variables would look like if the array had something like 50 or 100 values.

NOTE: I’m aware that you could also use array_map() and explicitly cast the array as an object to accomplish the same thing. That’s not the point. We’re illustrating a concept, here. Play along.


The Problem with Form Processing

Make form processing a breeze.

Now that you know how to use variable variables, we can move on to the meat and potatoes of this article, which is the idea that incorporating a lookup array instead of multiple controller files or a switch statement can save you a lot of extra maintenance, repeated code, and headache in general.

To illustrate our concept, we’re going to use the idea of form processing. This is an essential aspect of web programming, and can also be one of the most tedious areas of any project.

However, after reevaluating your coding habits, you can potentially make form processing a breeze.

Frequently, either an individual file is created for each form to be processed, or a switch statement is used. In this section, we’ll go over how both solutions might be implemented, and then we’ll examine a solution using variable variables, and how it can improve your projects.

A Working Example with Multiple Form Processing Files

An often used method for handling form submissions is to create a whole new file to handle each form’s data separately.

Take, for example, these three forms that update a user account with a new name, new email, or both:

<form action="assets/inc/ex1-form1.php"
      method="post"
      id="ex1-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex1-form2.php"
      method="post"
      id="ex1-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex1-form3.php"
      method="post"
      id="ex1-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

Each of these forms points to a different processing file. So what does each of these files look like?

Processing form 1 (assets/inc/ex1-form1.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_name();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Processing form 2 (assets/inc/ex1-form2.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_email();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Processing form 3 (assets/inc/ex1-form3.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_both();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

As you can plainly see, the example files above are duplicating a ton of code. Expand this to 15 forms on a site, and you’ll quickly find that maintenance could become a nightmare.

The Account Class

As you can see, the processing files are creating an instance of the class CopterLabs_Account. This will be a very simple class that outputs information about a form submission.

Here’s the code for the class (assets/inc/class.coperlabs_account.inc.php):

<?php

/**
 * A simple class to test form submissions
 *
 * PHP version 5
 *
 * LICENSE: Dual licensed under the MIT or GPL licenses.
 *
 * @author    Jason Lengstorf <jason.lengstorf@copterlabs.com>
 * @copyright 2011 Copter Labs
 * @license   http://www.opensource.org/licenses/mit-license.html
 * @license   http://www.gnu.org/licenses/gpl-3.0.txt
 */
class CopterLabs_Account
{

    public $name = NULL,
           $email = NULL;

    public function save_name()
    {
        $this->name = htmlentities($_POST['name'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nName: " . $this->name . "\n";
    }

    public function save_email()
    {
        $this->email = htmlentities($_POST['email'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nEmail: " . $this->email . "\n";
    }

    public function save_both()
    {
        $this->name = htmlentities($_POST['name'], ENT_QUOTES);
        $this->email = htmlentities($_POST['email'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nName: " . $this->name . "\nEmail: "
                . $this->email . "\n";
    }

}

You can try out this code at Example 1 on the demo page.

A Working Example with a Single Processing File and a Switch Statement

Another popular solution for form processing is to consolidate all the processing scripts into one file and determine what to do with the data using a switch statement.

The switch approach commonly employs a trick in which a hidden input is added to the form containing an action to be taken upon submission. This
action is then used to determine what to do with the form.

Here are the same three forms, from above, with actions added, all pointing to a single processing file:

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-name" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-email" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-both" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

And the new processing file looks like: (assets/inc/ex2-switch.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Sanitize the action
    $action = htmlentities($_POST['action'], ENT_QUOTES);

    // Use the new 'action' hidden input to determine what action to call
    switch( $action )
    {
        // Form 1 handling
        case 'update-name':
            $output = $account_obj->save_name();
            break;

        // Form 2 handling
        case 'update-email':
            $output = $account_obj->save_email();
            break;

        // Form 3 handling
        case 'update-both':
            $output = $account_obj->save_both();
            break;

        // If no valid action is found, something isn't right
        default:
            die( 'Unsupported action.' );
    }

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\nAction: ", htmlentities($_POST['action'], ENT_QUOTES),
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../#ex2">Go back to example 2</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

You can see this in action by visiting Example 2 on the demo page. This is a marked improvement over using multiple forms, but you can see that we’re still duplicating some code.

On top of that, it’s a personal preference of mine to avoid switch statements whenever I can. This is due to the fact that switch uses loose comparisons ('a string' will trigger case 0 because a string evaluates to 0 if you convert it to an integer) and is extremely easy to turn into spaghetti code.


Fixing the Problem: Lookup Arrays and Variable Variables

As we’ve seen so far, both of the above solutions have their drawbacks, and require duplicate code. Imagine if there were a dozen or more forms on the site — not pretty.

To address this issue, we can use a concept called a lookup array, which maps the actions passed from the form to a method called on the object.

Yes, you could set the action as the method name, but that allows a bogus form submission to call any public method. Making the array a key-value pair is a small step to add a little more control without much extra work.

A Working Example with a Single Processing File and a Lookup Array

Using our knowledge of variable variables from the beginning of this tutorial, let’s modify our demo to use a lookup array.

Modify the three forms to point to a new controller file:

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-name" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-email" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-both" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

Next, put together the processing file that will handle form submissions (assets/inc/ex3-lookup-array.php):

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Sanitize the action
    $action = htmlentities($_POST['action'], ENT_QUOTES);

    // Set up a lookup array to match actions to method names
    $lookup_array = array(
        'update-name' => 'save_name',
        'update-email' => 'save_email',
        'update-both' => 'save_both'
    );

    // Make sure the array key exists
    if( array_key_exists($action, $lookup_array) )
    {
        // Using variable variables, call the proper method and store the output
        $output = $account_obj->$lookup_array[$action]();
    }
    else
    {
        die( 'Unsupported action.' );
    }

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\nAction: ", htmlentities($_POST['action'], ENT_QUOTES),
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../#ex3">Go back to example 3</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Check this out on the demo page by trying out the forms on Example 3.

Since we set the action as the key in the array, we use array_key_exists() to ensure that the action is valid. Then, we use the value that corresponds to the action as the method name. Notice that we added the parentheses after the value to make sure it’s executed as a method.

The addition of the lookup array keeps the code concise, simple, and clear (once you get the hang of variable variables).


Summary

Used responsibly, lookup arrays can make your scripts far easier to update and maintain when you combine them with variable variables.

How do you think you can integrate lookup arrays and variable variables into your projects to make maintenance easier? Let me know in the comments!

Want to talk specifics? Discuss this post on the forums.

January 24 2011

05:23

25 Excellent Examples of Forms in Web Design

A form can be a very important part of a website. From really simple and direct ones, to fancy, colorful and creative, there is a form style for each site. When thinking about the interface design of your site, this is certainly an element you should focus on. From Login/SignUp forms, to contact forms and other types of forms, we need to keep in mind that the point of those forms is to get the user’s attention and make them want to fill in the info. So here are some excellent examples of forms in web design.

Awesome

forms06

forms07

Foundation Six

forms09
forms10

Wanken

forms13
forms14

Visual Republic

forms15
forms16

Andrew McClintock

forms17

Chris Woods

forms18

bio-bak

forms19

Vincent Mazza

forms20

Ed Peixoto

forms21

Christian Sparrow

forms22

olga designs

forms23

Krista Ganelon

forms24

Forever Heavy

forms25

Cornerd

forms26
forms27

Justdot

forms28
forms29

sikbox

forms30

Justalab

forms31
forms32

Buffalo

forms33
forms34

Sprocket House

forms35

Gardener & Marks

forms36

Pentagon

forms11
forms12

Gams

forms08

All Creative

forms01

forms02

Creditable

forms03

Gowalla

forms04

forms05

Source:

Pattern Tap
Minimal Sites
The Best Designs

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...