preview

20+ HTML Forms Best Practices for Beginners

Working with XHTML forms can be somewhat daunting; they not only use some niche HTML elements, but also blur the line between static content and user interaction. Let’s review some things to remember when creating your next form.

Good HTML forms require attention on at least four points:

  1. Semantics
  2. Accessibility
  3. Functionality
  4. Design

Forms can be difficult and sometimes even annoying for users;
often, a form interrupts a user’s main focus and direction on a page:
they’re intent on purchasing that gift, or trying out your new web app,
not giving you their shipping address or coming up with yet another password.
These tips will make forms easier for you as a developer/designer, and
them as a user.

Semantics

1 : Use fieldsets to encapsulate similar fields

Generally, forms are made up of inputs inside form tags. When you’ve
got a lot of fields that the user must fill out, it can be easier for
both the user and you, the developer, to keep track of input by using
fieldsets. The perennial example of this is using fieldsets to separate
a billing address and a shipping address.

<fieldset>
    <span>Billing Address</span><input type="text" />
    <span>City</span><input type="text" />
    <span>Province</span><input type="text" />
    <span>Postal Code</span><input type="text" />
</fieldset>

<fieldset>
    <span>Shipping Address</span><input type="text" />
    <span>City</span><input type="text" />
    <span>Province</span><input type="text" />
    <span>Postal Code</span><input type="text" />
</fieldset>

2 : Label Fieldsets with Legends

It hardly makes sense to use a fieldset without giving it a clear name.
We can improve the code above by using the legend element to title our
fieldsets. The fieldset element has a border by default, and the legend
will lay itself over that border.

<fieldset>
    <legend>Billing Address</legend>
    <span>Address</span><input type="text" />
    <span>City</span><input type="text" />
    <span>Province</span><input type="text" />
    <span>Postal Code</span><input type="text" />
</fieldset>

This results in the following:

legend

3 : Name your Inputs

If you want to pass form data to a script, each input element needs
to have a name; if you are using PHP, these names will become the keys
to a super global array, usually $_POST or $_GET.

<fieldset>
    <span>Billing Address</span><input type="text" name="billAddress" />
    <span>City</span><input type="text" name="billCity" />
    <span>Province</span><input type="text" name="billProvince" />
    <span>Postal Code</span><input type="text" name="billPC" />
</fieldset>

4 : Use the Label Element

Let’s continue improving that code; there’s nothing inherently wrong
with using a span to label the inputs, but the label tag is a born match for inputs.

<fieldset>
    <legend>Billing Affress</legend>
    <label>Address</label><input type="text" name="billAddress" />
    <label>City</label><input type="text" name="billCity" />
    <label>Province</label><input type="text" name="billProvince" />
    <label>Postal Code</label><input type="text" name="billPC" />
</fieldset>

5 : Give Labels the For Attribute

I really like the ‘for’ attribute; it provides a way to bind a label to an
input. The value of ‘for’ should be the same as the id of the input you want
to bind it to.

<fieldset>
    <legend>Billing Affress</legend>
    <label for="billAddress">Address</label><input type="text" id="billAddress" name="billAddress" />
    <label for="billCity">City</label><input type="text" id="billCity" name="billCity" />
    <label for="billProvince">Province</label><input type="text" id="billProvince" name="billProvince" />
    <label for="billPC" >Postal Code</label><input type="text" id="billPC" name="billPC" />
</fieldset>

At first, this is one of those things that only seem to affect your
code’s quality, but they do a special job in the visible content: when
the for attribute is defined, the label becomes a ‘clickable’ area that will
focus the input. For example, clicking the label of a text input will focus
your cursor in the box; clicking the label of a checkbox will check (or uncheck)
the box.

6 : Use optgroup to categorize options

If you have a lot of options in a select, it’s usually better to group
them into optgroups. <optgroup> is a little-known element that will indent
options and give them a title. Note that the label attribute is required.

<select>
<optgroup label="USA">
    <option>Alabama</option>
    <option>Alaska</option>
    <option>Arizona</option>
</optgroup>
<optgroup label="Canada">
    <option>Alberta</option>
    <option>British Columbia</option>
    <option>Manitoba</option>
</optgroup>
</select>

This gives us the following results:

select

7 : Always assign complete attributes

When working with forms particularly, it’s tempting to write like this:

<label for="live">Living?</label>
<input name="live" id="live" type="checkbox" checked disabled />

Yes, this does what it’s supposed to do. No, you shouldn’t code like this!
It isn’t standards-compliant. Whenever you are adding attributes to an element,
don’t cut corners.

<label for="live">Living?</label>
<input name="live" id="live" type="checkbox" checked="checked" disabled="disabled" />

8 : Consider using Buttons instead of Submit Inputs

Generally, <input type=”submit” /> has been the universal submit
button. But HTML has a <button> element. Why would you use it? Well, it’s
generally easier to style buttons; also, you can put images within a button,
so it really offers more flexibility. You can read more in
these
two articles.

Accessibility

9 : Put tabindices on your inputs

It’s definitely easier to tab through a form than it is to use your mouse . . .
however, by default, your user will tab through in the order they are written in
the HTML. If this isn’t the order you want them to go through the inputs, you can
easily add the tabindex property to your inputs; tabindex takes a number value, and will
hop to the input with the next highest value when you hit that tab key.

<input type="text" tabindex="2" />
<input type="text" tabindex="1" />
<input type="text" tabindex="3" />

10 : Define accesskey when appropriate

The accesskey attribute creates a keyboard shortcut that will focus that
input: the shortcut is Alt (Option) + the accesskey value. Obviously, you wouldn’t
put an accesskey on every input, but it would certainly be useful on, for example, a search box.
Don’t forget to let users know about the shortcut; often this is done by underlining
the letter, as it’s usually part of the label.

<label for="search"><span class="shortcut">S</span>earch</label>
<input type="text" name="s" id="search" accesskey="s" />

11 : Use good focusing techniques

You could argue that this point is as much on the side of design as it is accessibility.
It’s always nice if a form field (usually a text box, in this case) changes colour when it’s focused, but for the visually
impaired, it’s almost a requirement if they are to use the form successfully.
To this end, you can use the hover psuedoclass in your CSS; this will work in all
common browsers except IE7 and down. You can also use JavaScript for this;
jQuery has a hover
event
.

input[type=text]:hover {
    	background-color:#ffff66;
    	border-color:#999999;
}

12 : Consider people using Screen Readers

Since forms have the tendency to be so tedious, everyone likes a well-designed form.
But don’t let a fancy form ignore screen readers: always make sure your inputs are
clearly labeled. If you don’t want those labels to show (maybe you are labeling text
inputs with values that disappear on focus), you can remove them from the visual presentation
(don’t use display: none, though;
there are better ways
). Also, screen readers generally associate the text directly
before an input to be the label for the input. The exceptions to this are radio
buttons and checkboxes.

Functionality

13 : Use the right Content Type

In most cases you won’t need to put the enctype attribute on your form
tag; it will default to “application/x-www-form-urlencoded.” However,
when you have a file input, which will allow the user to upload the file,
you need to use “multipart/form-data.”

<form action="verify.php" method="get" enctype="multipart/form-data">
    &tl;label for="avatar">Upload your Avatar : </label>
    <input type="file" name="avatar" id="avatar" />
</form>

14 : Know when to use Get and when to use Post

A form can send its data by two methods: get and post; you define
one in the method attribute on the form tag. What’s the difference,
and when should you use them? Ignoring what goes on at the server,
the main difference is the way the browser sends the information.
With get, the form data is send as a query, visible in the url. So
this form . . .

<form action="you.php" method="get">
    &tl;label for="fname">First Name</label>
    <input type="text" name="fname" id="fname" value="Bill" />
    &tl;label for="lname">Last Name</label>
    <input type="text" name="lname" id="lname" value="Gates" />
</form>

. . . would result in this URL when submitted: http://www.example.com/you.php?fname=Bill&lname=Gates

When you use post, the data is sent in the HTTP request header.
That way, it’s not visible to the average user. So which should you
use when? Post is better for sensitive data (like passwords) and any
data that will generally change something (e.g. add a record to
the database). Also, post is your only option if you’re uploading
a file. Get is great for querying the database, and other requests
that don’t have a lasting affect on anything (“idempotent” the spec
calls it). Really, I’ve just scratched the surface on the differences
here: there are
other
articles that go into this in-depth.

15 : Validate on both the Client and Server

validate

Validation is the bane of forms. But it’s best to check the input both on
the client and on the server; validating in the browser allows you to warn
the user of mistakes before they submit the form, which requires one less
transaction with the server. However, always be sure to validate on the server
as well, for security’s sake.

16 : Give your Users Smart Warnings

This goes hand in hand with the previous best practice. Too many times I’ve
submitted a form only to be told “Fields were not filled correctly.” Can you spell
vague? Once you’ve determined that your user has made a mistake, let them know as
soon and as clearly as possible. Put your error messages close to the bad field,
and let your user know what’s wrong with their entry. I like using the jQuery’s blur()
event for this: as soon a user hops to the next box, the previous one is validated.

errors

17 : Consider using AJAX to submit

Many times, submiting a form results in a simple message: “Thank you,” “Check your
email for confirmation,” or “We’ll get back to you when we can.” When that’s the case,
what better place to use AJAX? You could just fade out the form, send the data with
jQuery or (YOUR FAVOURITE LIBRARY), and fade in your message.

ajax

18 : Make sure your form works without Javascript

Maybe this should have gone under accessibility; although the last couple of tips need
JavaScript to work at all, make sure your form is completely functional without them. This means a regular
form submit, server-side validation, and good errors after a page reload.

Design

19 : Style Forms Consistently

I’m no designer, and I don’t pretend to be, but I do know this much: don’t fling your
form fields carelessly around. Your form should be consistent in its styling. Decide whether
your labels will be to the left or right (or perhaps above or below) of the fields, and stick
with it. Make all your text inputs and textareas the same width. Space all your fields equally.
Keep at least one edge of all boxes aligned. The tuts+ comment forms are great examples of well-styled forms.

comments

20 : Consider using JavaScript to Consistently Style Forms over Different Platforms

With upteen browsers/operating system combinations, form element consistency is hardly
possible . . . without the help of a bit of JavaScript. If you want your forms
to look the same on almost every browser, check out the
jqTransform jQuery plugin,
a plugin aimed directly at this compatibility problem. Simply include it, call it, and adjust the included css file
to your taste; it works with IE6+, Safari 2+, Firefox 2+, and Chrome.

21 : Be inspired by others

If you’re having trouble coming up with that unique form design for your site, go for a
little inspiration! Smashing Magazine has a
great roundup of forms,
and Smileycat’s “Elements of Design” Gallery has a bunch of
Blog Comment Forms worth checking out.

Conclusion

22: Look forward to HTML 5 Forms

HTML 5 has some great features for web forms. Two of the most exciting ones are new types
for inputs (like url, email, and date) and the datalist element, which can be used for easy
autocomplete. When these and other parts of the spec get implemented, dynamic forms will be
much easier!

Website forms can be challenging, but I hope these tips will help you make your forms stand
out from the rest. Have a good tip that I didn’t mention? Let’s hear it in the comments!

You Also Might Like


Tags: formshtml
Add Comment

Discussion 116 Comments

Comment Page 2 of 3 1 2 3
  1. axomedia says:

    Nice tut as alway! Thank you!

  2. Chanel says:

    Great tut. Lucky to be a member and enjoy this type of info daily.

  3. Devan says:

    If you put a label around an input tag that is a radio button if the user clicks on the text in the label it will auto select the radio button.

    Yes

    If the user clicks on yes, it will select the radio button.

    +1 Usability

  4. Stoner says:

    great tutorial
    thx

  5. Liam says:

    Will just copying the code here actually submit the info in the form?
    Am I right in thinking somehting like FormMail(?) is needed or something or something (help!)?

  6. Kent says:

    Congrats. I thought I knew enough about form markup but I sure learned a lot from this tutorial.

  7. Been doing web dev for 3 years now, and i’d never used ‘Optgroup’ tag but will now! thx ever so for yet another great tut

  8. zahid says:

    Really helpfull for begainers……….

  9. Jason says:

    Cool article. I’ve seen so many people post about how to style forms and make them look pretty. But you got right down to the core !

  10. Muthiulhaq says:

    thanks, very nice

  11. nelson kelem says:

    I WOULD LIKE TO SEE A TUTORIAL HOW TO SECURE (CONFIGURE SECURELY) PHP AND APACHE SERVER FOR A PRODUTION ENVIRONMENT. MOST PROBABLY PHP 5.x AND APACHE 2.x WITH ADVICE ON WHAT IS THE IMPORTANT BITS.

  12. เพชร says:

    apart from the typos, this is a great tutorial.

  13. I have just bookmarked this to use when I next design a form. I have designed manu forms in my time but there is still stuff here that I didn’t know about!

    Tha accessibility article in particluar has been brilliantly produced.

    Again, many thanks for the superb work.

  14. Kendall Sanford says:

    Great stuff. Found some things useful.

  15. Rollout says:

    You dont mention the “Fieldset background color bleed bug” that exists in IE6 – (Yes, I still have to design for IE6) it requires a couple o’ hoops be jumped through in order to make it look right. So, consider this when using the
    Fieldset and Legend tags.

  16. justintime says:

    Nice revisit…just curious
    why did you turn into ?

    Also, I have seen many arguments that forms *can* be styled using tables vs. li/dt and that they are nothing more than ‘interactive tabular data’. Personally, I find it much harder to style/position form elements using lists than tables.
    Any thoughts on that?
    Thanks!

  17. priya says:

    i appreciate it more every time i see.

  18. Thank u so so much. I appreciate it more every time i see

  19. Rajan Singh Patialvi says:

    Thanks sir, for nice & useful sharing..

  20. Huckleberry says:

    This is a great tut for beginners. Another great thing I do is use a little program called Forms to Go, by Bebosoft. I don’t know much PHP, but I’ve learned alot of valuable info just from this program, not to mention it writes your scripts for you, just drop in your form, do the settings you prefer, and it spits out a great PHP, ASP, or Perl scipt. It handles the confirmation emails to user & owner, can even do HTML confirmation emails, along w/ Database dumps, Captacha, and lots of other useful things. Pound for pound, my favorite program!
    Thanks for the great tut too!

  21. Antidote says:

    Great Job, gives a clear overview to basics and important things that should know about forms!

  22. Ashish Shinde says:

    great this tutorial very helpful. keep it up

  23. alan says:

    Very nice article. Thanks a lot!

  24. BAD says:

    NEVER USE TABINDEX ON FORM FIELDS! THIS IS HORRIBLE FOR SCREENREADERS!

  25. Oning says:

    how to make a comment form on the web??
    i i hope can you tell me source code ??

    thank`s before

  26. Joao Aliano says:

    Cheers! Clear and well put together tutorial. Thanks Andrew and NetTuts+

  27. Juan Carlos says:

    Excellent tips!! Link already bookmarked but just wondering if points 17 and 18 are compatible, since in the first you encourage to use AJAX to submit and in the latter you state to bear in mind the accessibility by avoiding the usage of JavaScript.

    Thanks

  28. Thanks for your advices… I’m looking for creating a dedicated form for a website and this is very helpful for me !

  29. Xcellence IT says:

    Awesome explanation

    Thanks

  30. Bryan says:

    This is another great reference!
    I love the in-depth analysis on mostly every tutorial Nettuts has.

    Keep it up! And I will definitely be back tomorrow ;)

  31. skhot says:

    In #20, i’ve been noticing some tom-foolery with jqtransform and the latest firefox. I’ve used it in several projects but am considering other options. Anyone else?

  32. Prog4rammer says:

    Thanks a lot for Your Great tutorial cool :)

  33. Sam says:

    Won’t using a button input type instead of a submit input type necessitate the need for javascript to submit the form? If so #8 conflicts with #18..

  34. Jason says:

    This is great information, but what exactly is a “billing affress”?

  35. Srinivas Reddy says:

    Nice..very helpful…clears all the fundamentals..thanks a lot…

  36. very good tutorial, will be making use of this in future!

  37. cinek2 says:

    nice tutorial! thanks!

  38. Emin says:

    I always see people using only :hover as a focusing technique. But there is also the pseudoclass :focus which is so often forgotten. Even this article doesn’t mention it and I don’t know why. It’s doing a similar effect like :hover but without the mouseover. If the cursor is focused on that element, like when using tabulator in forms, like I do all the time, this could help a lot.

  39. Jon says:

    Thanks for this great list of tips and best practices, I already use a few of them, but this has really opened my eyes

  40. You forgot to mention you can alternatively wrap elements with the label element like this:

    username:

    Less code, more logic and more accessible too.

  41. Brandon says:

    thanks for the inspiration!

    i built the following Gr8 Form and Gr8 Form with Validation.
    Made it easy for the user adding the code, only 3 steps and it send directly to any email the user chooses.

    http://www.icodesites.com/gr8-code/index.php

  42. Projeycb says:

    Wow dude! No need for those codes use form builders instead here is an example http://www.jotform.com/

  43. Aidan Boyle says:

    Great tips thanks a lot!

  44. Alexzandro says:

    This is a gr8 tutorials for beginners..

  45. Baiju says:

    Very nice article. Thanks

  46. Nice article, Thanks Andrew it is really helpful for beginners like me.

  47. Really great post and very help full for Web Designers!

    Thanks.

Comment Page 2 of 3 1 2 3

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.