Sneaky Abstractions

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

FormHelper

Posted on September 28, 2007 23:28, 5 comments. Tagged with javascript.

An unobtrusive "unobtrusive" answer to the very frequently asked question “how do I create a dropdown that fills out another dropdown”.

<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>

And it just works.

Download now for the low price of nothing and get one extra feature for no added cost! But wait, there’s more! Download within the next ten years and receive the practical Checker for free!

Comments

Atom feed

By Jason at

Thanks for this! Was looking for something like this most of the day and just saw this post on planetrubyonrails.com

By dan at

Great! May be you can show method to auto select first element after first select some option? For ex.: in first select box: I choose “1” and in second selected box auto set 1.1, but then I click in first select “2” or “3” , and click again “1”  then in second select I see 1.2 , but I want see 1.1 :) Sorry for my english ) please help me

By Tore Darell at

Dan: Yes, that would make sense. I’ve updated the script to automatically select the first option in a list when the options are changed.

By Steven Garcia at

First of all thanks for writing this up. I am trying to move my JS into unobtrusive waters and stuff like this is a godsend.

Secondly, I am having a bit of trouble adapting this to my needs. Right now you seem to be using dom class hooks on the first select tags and are setting the target select by its dom id.

But what if I want one select list to update all the select lists on the page with a certain class?

How should I modify the js to loop through all the classes instead of targeting one id?

By Tore Darell at

Steven: You’ll have to write some custom JS for that, but it’s definitely doable, if I understand what you’re trying to do.. I created a small test document that demonstrates it. If you look at the source, in the window.onload function, you’ll see that it manually creates SelectUpdater instances based on the class name..

Leave a comment

OpenID

Or..

Old school

Super Disco Breakin