From the archives

An archive of blog entries since 2004 on subjects including CSS, web standards, accessibility, website design and development.

Trimming form fields (repost)

Web forms often ask visitors for non-essential information, but long and complicated forms can hinder a sales or sign-up process. Wouldn’t it be cool to give users the option to hide these optional fields at their own discretion. (This entry was originally posted in 2004 and has been updated in 2009.)

Why am I republishing this article now, five years after I originally wrote it? One reason is that this article is still widely linked to and is one of the most read pages on this site. Also, because of the rise of jQuery, I would love someone much cleverer than I am to rewrite its Javascript (originally written by James Edwards) as a plugin for that framework. Who will volunteer for that task? Now, for the (updated) article.

Start by writing an semantic, with only a sprinkling of additional mark-up. Then add minimal CSS to provide users with a method for removing the optional fields. We will also ensure that the form works for users whose browsers or user-agents do not support Javascript or CSS to ensure that the form is accessible.

Before we crack on, here is a look at the finished result.

Mark-up

Set up a basic form containing structured elements.

<form id="example-form" method="post" action="">
<fieldset>
<legend></legend>
<label></label>
<input />
<br />

Etc.

You might notice that we've added <br />s after each form element. These are not semantically necessary, but will improve the layout when viewing with only browser default styles. If you are not worried about this plainly styled layout, these can safely be removed.

Enabling the field toggling

To enable field toggling, enclose optional fields and their respective labels in paragraphs with a class attribute value of optional.

<p class="optional">
<label for="fm-forename">First name</label>
<input type="text" name="fm-forename" id="fm-forename" />
<br />
</p>

Now add an empty paragraph with a unique id above the form, this will become our toggle switch.

<p id="linkContainer"></p>

Although we will use CSS to visually identify all required fields, such presentation is useless to text browsers or screen-readers. Whilst generated content would be the preferred solution, the lack of support in Internet Explorer 7 requires means that we should add Required to each required element label.

<p>
<label for="fm-surname">Surname (Required)</label>
<input type="text" name="fm-surname" id="fm-surname" />
<br />
</p>

Trimming form fields

First make use of that empty place holder. The anchor and link text are only generated if Javascript is enabled. In the script, generate the link text that is displayed as the page loads.

toggle.appendChild(document.createTextNode('Remove optional fields?'));

Then generate the display and remove fields link text.

this.firstChild.nodeValue = (linkText == 'Remove optional fields?') ?
'Display optional fields?' : 'Remove optional fields?';

Finally set the class name for all optional fields to optional.

if(tmp.className == 'optional') {
tmp.style.display = (tmp.style.display == 'none') 
? 'block' : 'none'; }

That's it, a completed form that gives users the option to hide optional fields. Download the CSS and Javascript. Anyone up for the challenge of translating Trimming Form Fields into a jQuery plugin?

Original comments

  1. #1 On July 6, 2004 11:04 PM Ryan Brill said:

    Very nice. Definitly enhances the usability of long forms, as people can quickly see what they need to fill out and what is optional.

  2. #2 On July 6, 2004 11:07 PM andrew said:

    Very impressive, user-friendly, and useful. This can really come in handy with the super-beefy "Review Your Case" form for lawyers or a contact form with additional optional survey information.

  3. #3 On July 6, 2004 11:10 PM Justin French said:

    You can possibly hear my applause from way down here in Australia right now. Very nice work. Of course, it could be argued that if it's all optional information, it could just be removed from the form forever, saving everyone a lot of grief, but this technique has a lot of other applications, like a "show full posts" or "show only excerpts" button on a blog. The dynamic JavaScript link is the perfect icing on the cake too.

  4. #4 On July 6, 2004 11:32 PM Colly said:

    Hmm, that's going into the content management system tomorrow Andy. For most projects, users seem to want to get registration out of the way and start using a site, wishing to fill out their profiles at a later date, or once they've seen what others do. This is where such a method comes in handy. I've been using a DOM expand/collapse on other elements for a while, but you should see how unsemantic it was. Hey, what about a definition list for the form data - get rid of those break tags for good (guess who's reading Cederholm at the moment?!)

  5. #5 On July 7, 2004 12:40 AM Keith said:

    That's great! I'm all about simpler forms as I find them not only one of the harder parts of my own user-experience on the Web, but also one of the harder parts of Web design and development. My rule is that if you don't use a bit of information, you shouldn't be asking the user for it. Then again, what I consider essential isn't the same as what my stakeholders and clients think is essential. Techniques like this, when applied based on well thought out goals help us to achieve that hard to reach balance good Web designers strive for. Nice work.

  6. #6 On July 7, 2004 02:39 AM Cameron Adams said:

    I can just see my nemesis in the marketing department now: Oh yes, another form with which to deviously collect the information which our CRM database feeds on (laughs maniacally) Hang on, what's this button here? WHAT!? Customers able to easily sidestep my malevolent collectors of personal information? (rings Cameron). Remove it, foul underling!

  7. #7 On July 7, 2004 10:17 AM Tim Parkin said:

    It's very cool but getting management to sign off on look, we can make it easier for the customer to avoid our crm system and then we won't have to send out direct mail to them might go down badly. How about a favelet that understands what form elements have been marked as essential using asterixes etc (maybe covering 90% of occurences on the web through fuzzy matching) that you can then use on ANY form. You could even use javascript to force the tab order to skip the ones you don't want. I'd love that on my google bar!

  8. #8 On July 7, 2004 10:52 AM Steve Potts said:

    Andy, I like this. A lot. From an accessibility perspective - and like many people here know - providing accessible content isn't just about ticking boxes or (heaven forbid) relying on running an automated evaluation tool.
    This is a solution that reduces complexity. Reducing complexity is of benefit to those visitors with cognitive disabilities just as much to those with not much time to spend on a particular task, such as form filling. Not enough time? Yes, it's a disability too. Indeed, the solution does work in JAWS, and it (peculiarly) fails in IBM HPR, though gracefully without catastrophic effect, but this is much more than covering all browsers; it's a concept, and a jolly good one at that. Well done.

  9. #9 On July 7, 2004 04:35 PM Richard@Home said:

    Marvelous stuff :-) One minor ammendment might be to chage the line:

    if(tmp.className == 'optional')

    to

    if(tmp.className.indexOf("optional")!=-1)

    as this will allow you to specify multiple classes in your paragraphs.

  10. #10 On July 8, 2004 02:01 AM Simon Willison said:

    Very nice! I like the idea (though I doubt marketing people will) and the implementation is very clean. That said, it's possible to achieve the same effect without having to loop through all of the divs on the page: dynamically change a class on an element containing all of the divs you want to toggle, then target them and alter their visibility using a CSS rule. I've written the technique up on my SitePoint blog (using your code as a base) as it's a really powerful concept, and one I'd never really thought about much before. Thanks for the inspiration!

  11. #11 On July 8, 2004 08:08 AM Jan Korbel said:

    I like this idea and it is beuty to see how simple that form looks. BUT in reality, if you want to let your users to switch off the feilds so easily, why to even put them there? I mean, most of the users will just switch them off and not fill-in them. Am I wrong?

  12. #12 On July 8, 2004 09:53 AM Colm said:

    Interesting article.

  13. #13 On July 8, 2004 04:54 PM Jules said:

    Andy: Pretty cool. Hmm, let's see how this adds up: Accessibility advocate and guru + XHTML guru + CSS guru + JavaScript guru = ??? damn, my calculator blew a fuse. Praise aside, I am not convinced though that JavaScript, however, sophisticated, and Accessibility go hand in hand in this type of scenario. If a JAWS user clicks on the hide optional link, will the optional entries disappear? I recall reading that JAWS buffers a page within itself: if that is true, then a JAWS user does not benefit from the code and has to read through the content to determine what or what is not required. I should really do a test to confirm this but in the mean time, if anyone else can confirm or deny my assumption, that would be great.

  14. #14 On July 8, 2004 05:04 PM Colly said:

    In response to Jan's comment (and Keith's not-for-client perspective), I have built a few community sites where users definitely, definitely DO go back and start playing with the other form fields - think of download communities, membership-based forums etc. Initially the user is desperate to just get on board, later going back to interact more. Or, what if at first you don't need a particular field (say an alternative billing address) but later you do need it. Oh no - you can't, because all optional fields were outlawed in the Great Formfield Prohibition of 2004! It really does depend on the brief and what info you require, but it's simply not possible to ONLY provide required fields across ALL builds. Give users, clients and developers some choices...

  15. #15 On July 8, 2004 06:21 PM Jan Korbel said:

    Colly: Good thoughts, thanks.

  16. #16 On July 8, 2004 09:50 PM Patrick H. Lauke said:

    Good idea, but maybe a nitpicky comment: why use <p class="optional"> when you could use a semantically marginally more meaningful <fieldset class="optional"> instead?

  17. #17 On July 9, 2004 02:36 AM Malarkey said:

    @ Jules: Javascript guru? Thanks, but the fabulous Brothercake should take most of the credit for the Javascript parts of this column.

    @ Pat and Colly: I decided to wrap the form elements in <p>s as I wanted to hide specific fields rather than whole fieldsets and <p>s seemed more semantically neutral than <dl>s.

    @ Richard: I never expected that anyone would actually want to read my humble ramblings, let alone want to comment. On the next fiddle I'll look at the comment form again.

    @ Simon Willison: Wow, you are much cleverer than me, to be sure! But your solution has sparked a few ideas that I am going to experiment with. I'll report back here if anything useful turns up.

  18. #18 On July 11, 2004 08:21 PM SirGUI said:

    If it's not essential don't put it there. Saves your time, save my time.

  19. #19 On July 13, 2004 06:18 PM [m] said:

    Reminds me of http://www.quirksmode.org/dom/error.html and http://www.quirksmode.org/dom/usableforms.html.

  20. #20 On July 13, 2004 06:26 PM [m] said:

    And an explanation that goes with the second link: http://digital-web.com/articles/forms_usability_and_the_w3c_dom/

  21. #21 On July 13, 2004 07:27 PM Malarkey said:

    @[m]: If that is in fact your *real* name ;)

    Two good articles there that I had not come across before, thanks for adding them to the discussion.

  22. #22 On July 15, 2004 06:08 AM Pintu Sharma said:

    Very Nice and very differnt approach told in a unique way. Keep it up.

There have been 10 new replies

  1. 1

    James Sinclair

    I had a quick go at creating a jQuery plugin to do it. Demo can be seen at http://jrsinclair.com/toggle_optional_fields/

    Plugin source code can be found at http://jrsinclair.com/toggle_optional_fields/jquery.toggleOptionalFields.js

    Apologies for GoDaddy badness

    2nd Nov 2009
  2. 1

    Régis Kuckaertz

    I can see a tremendous lot of applications for this, thanks for reposting!

    From a structure perspective, I’d argue that complex forms, i.e. long enough to require optional fields instead of getting rid of them, would benefit from being divided into sections in each of which one would find corresponding required and optional fields.

    You guessed I’m suggesting using fieldsets to break up the form in pieces, and details to group optional fields. Even though the latter was not intended for such uses, I think its semantic matches closely your idea.

    What’s your opinion?

    (This comment was left on For A Beautiful Web)

    2nd Nov 2009
  3. 1

    Jason O'Brien

    James, good work.

    My only criticism is that both Andy’s original idea and your jQuery plugin take control away from the designer. I would suggest giving up control of the link container and link text and letting people choose a class or id they want to act as a trigger, so they could use something like:

    $(’.LinkofMyChoosing’).toggleOptional();

    I’m not sure I see the value in having both a container for this link or having it generated on the fly… what overall benefit does that have?

    2nd Nov 2009
  4. 1

    Amrinder Sandhu

    Good Work!

    I would suggest remove the *required* word when the required fields are displayed, rather mention this -required- with above text saying: “All fields are required. (Display optional fields)”

    This way, I think, the form labels will look clean.

    What do you think?

    P.S. Suggestions are based on Luke’s book: Web form design - Filling in the blanks.

    (This comment was left on For A Beautiful Web)

    2nd Nov 2009
  5. 1

    Elliott

    Ahoy!

    I think this can be done with simpler markup- jquery can do all the required traversing keyed off the field input names.  And since the obvious overlap with this would be the actual form validation, I took it a step further and structured the markup to serve both purposes.  I gave it a go at the following:

    http://elliottrounsavall.com/forms.html

    Note that I removed the container p elements and input ids.  Were you to add additional nodes into the markup, you’d may need to change the jquery code that finds the corresponding field elements.

    2nd Nov 2009
  6. 1

    Shaun hare

    nice idea,

    So much so I was inspired to write the jquery plugin requested

    See - http://shaunhare.co.uk/formalarkey/  for the plugin source
    @jason it also offers the ability to change the text of the messages and define your own link

    Andy so as to do it justice (from a design perspective) if you will allow me I am happy to put up a demo page using your original source :)

    2nd Nov 2009
  7. 1

    Andy Clarke

    James Sinclair: I had a quick go at creating a jQuery plugin to do it.

    — For your fist public plugin, that looks fantastic James.

    Elliott: I think this can be done with simpler markup- jquery can do all the required traversing keyed off the field input names.

    — Thanks for your help, that looks great. One of the most important aspects of the original trimming script was the fact that the toggle anchor was generated by JavaScript so it would only appear if scripting is available. I might be missing something (it’s been a long day), but is that missing from your version. Not being picky, I just want to be clear what I’m looking for.

    Shaun hare: Andy so as to do it justice (from a design perspective) if you will allow me I am happy to put up a demo page using your original source :)

    — Please do. And thanks so much for taking the time to help.

    2nd Nov 2009
  8. 1

    Ryan

    Looks great Andy. One tidbit I’d add, the optional fields looked inactive at first glance. Just a minor detail, but the styles around those inputs may confuse some users. :)

    2nd Nov 2009
  9. 1

    Elliott

    re: @andy

    - I missed that bit.  I’ve tweaked. Javascript doesn’t add the toggle anchor, it changes it from ‘display:none;’ to ‘display:block;’.

    http://elliottrounsavall.com/forms.html

    2nd Nov 2009
  10. 1

    Shaun Hare

    Good point about progressive enhancement Andy.
    To ensure people adopt this approach I have updated the code to prevent people adding their own link, they can still change the text. This will ensure the functionality only appears when js is available.

    Also added the demo thanks for allowing that, also apologies for incorrectly spelling your surname on the previous version of my page, please forgive.

    2nd Nov 2009
Commenting is not available in this weblog entry.

Tweet a reply using the hash tag #sn_1217

lawb

Some fantastic jQuery enhancements to Trimming Form Fields. Thanks! http://stno.me/s/n #sn_1217 (via @Malarkey)

Malarkey

Some fantastic jQuery enhancements to Trimming Form Fields. Thanks! http://stno.me/s/n #sn_1217

jamiei

Making forms less confusing by trimming them with jQuery. Good stuff really. (http://stno.me/s/n - via @Malarkey) #sn_1217

AndreiCurelaru

/RT @Malarkey: In case you missed it, an update to an old (still very popular) blog post (now with added jQuery) http://stno.me/s/n #sn_1217

Malarkey

In case you missed it, an update to an old (but still very popular) blog post (now with added jQuery) http://stno.me/s/n #sn_1217