2009-05-09

Strip unused form fields from form submissions

In my recent post "Why do we even need url shorteners?", I laid out a case for why URLs on the web are actually useful User Interface elements as well as wrote a little bit about how certain bits of history colluded to create needlessly long URLs as the norm. One specific case raised was that of HTML forms. Today I want to show you one way in which to simplify form submissions.
Many forms will contain many different input elements with very few of them actually being used at the same time. Most server-side software is equipped to accept the form even if some of the arguments are missing. It will just assume that the arguments take on the default values. For example, the Google advanced search interface has dozens of input elements. Just entering the query [gregable] and submitting the form will generate the following URL:
http://www.google.com/search?hl=en&as_q=gregable&as_epq=&as_oq=
&as_eq=&num=10&lr=&as_filetype=&ft=i&as_sitesearch=&as_qdr=all
&as_rights=&as_occt=any&cr=&as_nlo=&as_nhi=&safe=images

However, take away all of the default values for the field, and we get this completely equivalent URL:

http://www.google.com/search?as_q=gregable

However, browsers offer no easy way for the creator of an HTML form to craft these more usable URLs. Through javascript however, we certainly can. First, the demo. This demo is a stripped down version of the advanced search interface. I also added a checkbox and two radio buttons to illustrate some additional input types. If you fill out any field and hit submit, that set of fields and only that set of fields get submitted. If you are not running javascript this trick doesn't work, all the fields get submitted, but the form still operates. Give it a whirl:


How does it work? You can of course look at the source code. I define one short javascript function: stripFormDefaults. Then where I declare the form, I add onsubmit="return stripFormDefaults(this)". Nothing else fancy is going on.

The W3C tells us that when submitting a form, you only submit the values from the successful form controls. One of the rules for being successful is that the control must not be disabled. So our stripFormDefaults code just disables all of the form controls that we don't want to submit immediately before submitting. It then re-enables them in case the user hits the back button.


In order to know which form controls to submit, we take advantage of a little known set of form element properties that store the default value or state of each form control. Depending on the type of control element, this property is called defaultValue, defaultSelected, or defaultChecked. We simply compare the actual value of each form control with the default value and if they are the same, we disable that control before submitting.

0 comments: