Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

FormHelper

FormHelper is a collection of JavaScript helpers that I find useful in combination with forms.

Example and download

SelectUpdater

SelectUpdater is an unobtrusive implementation of the frequently requested feature “dropdowns that fill out other dropdowns”. That is, the contents of a select element is filtered based on the selection in another select. The way this is done is by giving the “source” and the “target” elements appropriate class names.

<select name="foo" class="updates:bar">
  <option value="1">1</option>
  <option value="2">2</option>
</select>
<select name="bar">
  <optgroup label="1" class="foo:1">
    <option value="1">1.1</option>
    <option value="2">1.2</option>
  </optgroup>
  <optgroup label="2" class="foo:2">
    <option value="3">2.1</option>
    <option value="4">2.2</option>
  </optgroup>
</select>

The above example will result in two select elements, “foo” and “bar”, where the options in “bar” will be filtered based on what option is selected in “foo”. The options in “bar” will be divided into @optgroup@s, each of which references an option in “foo”. The referencing is done by giving the group a class of “foo:id”, “foo” being the name and “id” being the value of the option it references. Note that “bar” provides all possible options by default, and that these will be filtered by the JavaScript. This is the unobtrusive part of it, and it will still work and maybe even make sense without JS.

Revealer

The Revealer shows and hides an associated element when the source element is clicked.

<label for="email" class="reveals:email">E-mail (optional)</label>
  <input type="text" name="email" id="email" />

The “email” input will be hidden until the label element is clicked.

Checker

Checker checks off a group of checkboxes all at once. This one is mildly obtrusive in nature, and I think it’s a pretty useless pattern, but I know a lot of people like it and think it provides some value. Consider it experimental.

<p class="checks:foo type:checkbox">
  Check all
</p>

<p>
  <label for="one">One</label>
  <input type="checkbox" value="1" class="checkable:foo" />
</p>

<p>
  <label for="two">Two</label>
  <input type="checkbox" value="2" class="checkable:foo" />
</p>

<p>
  <label for="three">Three</label>
  <input type="checkbox" value="3" class="checkable:foo" />
</p>

How to actually make it work

The script file won’t try to find your elements automatically, but it’s easy to do so. Each class has an onLoad method which will scan through the DOM to find elements with the right class names.

window.onload = function(){
  SelectUpdater.onLoad();
  Revealer.onLoad();
  Checker.onLoad();
};

You can of course put that in an onDOMLoaded type of event listener.

Comments

0 comments

They're justified and they're ancient, and they drive an ice-cream van