jump to navigation

selectedIndex is your friend on IE6 November 5, 2008

Posted by reidmix in Code, Example, Javascript.
Tags: , , , , , , ,
3 comments

While working on getting ChainedSelects to work on IE6, I realized there are multiple ways to set an option as selected.  Since ChainedSelects creates all the options for a pre-existing select, I first used the defaultSelected argument passed in the Option constructor:

option = new Option("name", "value", true);

Here, the third argument specifies whether the option is defaultSelected, when the select is first created or the form is reset. This worked fine in Firefox but IE6 blythely ignored it.  So I tried passing a fourth argument that specifies whether the option is currently selected.

option = new Option("name", "value", true, true);

Again, Firefox does the right thing but IE6 gets wacky and incosistently selects the correct option or sometimes does nothing at all.  It seems as if IE6 misses the “selected” message on the event queue, because it works only when i put some alert()s in there.

So I tried another way, by using the selected attribute after creating the option:

option = new Option("name", "value", true, true);
option.selected = true

Again, inconsistent behavior on IE6.  I went to the great oracle and asked google and tried setting the selected attribute to ‘selected’, ‘true’, and ‘yes’ all with no luck.  I wonder if this occurs because the select is pre-existing and is not newly created.  This led me to try out the selectedIndex attribute on the select element.

select = $('myselect')
select.selectedIndex = 3

Bingo!  This works in both Firefox and IE.  The index is 0-based as you would guess (0 is the first option is select.options).

Subselector, Moneypenny November 1, 2008

Posted by reidmix in ActiveRecord, Code, Database, Example, Monkey Patch, Plugins & Gems, Rails.
Tags: , , , , ,
2 comments

Building on Josh and Damon‘s idea of Hacking a Subselect in ActiveRecord, I wondered if you could bake this kind of functionality into ActiveRecord.  So Doug and I went digging into the rails code, and came up with a plugin that adds subselects to ActiveRecord which we call Subselector.

So far, it only works on the Hash version of conditions.

On a column you wish to perform a subselect, pass a hash with :in, :not_in, :equals, or :not_equals as the only key.  The value is any of the options you normally would pass to ActiveRecord find.  Notice that we make sure to select a single column with the :select option:

Critic.find(:all, :conditions => { :id => {:in => {:select => :id, :conditions => {:active => true} } } })

Although the example may be contrived, here, we are looking for a critics that are in a set of active critics. The SQL:

select * from critics where id in (select id from critics where active = false)

You can see by default it runs the subselect on the table of outer select.  It gets more interesting you want to run a query on another ActiveRecord model:

Critic.find(:all, :conditions => { :id => {:in => {:model => :rankings, :select => :critic_id, :conditions =>
  {:week => 39} } } })

Here we set :model to :rankings.  Rankings is the ActiveRecord model to perform the find, notice we select the :critic_id column, the SQL is:

select * from critics where id in (select critic_id from rankings where week = 39)

And of course you can always just pass a string as a value to the subselect:

Critic.find(:all, :conditions => { :id => {:not_in => 'select id from critics where active = true' } })

Here’s how subselector can be used with the original example:

Post.find(:all, :conditions => :id => {:in => { :select => :post_id, :conditions => {:blog_id => self.id}, :order => "published_at DESC", :limit => options[:limit] || 10, :offset => options[:offset])} }, :order => "published_at DESC")

UPDATE: Subselector now likes Condition Arrays and Named Bind Variables.

Just pass the hash as a bind variable and specify the type (in/equals) of subselect in the string, make sure to enclose your ‘?’ inside parentheses:

Critic.find(:all, :conditions => ['id in (?)', {:select => :id, :conditions => 'active = true' }])
Critic.find(:all, :conditions => ['id not in (?)', {:select => :id, :conditions => {:active => false} }])
Critic.find(:all, :conditions => ['id in (?)', {:model => :rankings, :select => :critic_id, :conditions => {:week => 39} }])

As you can see, you can format the subselect hash just as above and can specify another model to run the subselect on. If you prefer to use named bind variable hashes, they still work (yay) as you would expect. And you can assign the subselect using them:

Critic.find(:all, :conditions => ['id in (:subselect)', {:subselect => {:select => :id, :conditions => {:active => false} } }])

UPDATE 2: Now with no ActiveRecord breakage

We’ve run the rails ActiveRecord tests without any problems. Let me know if you find any problems.

These Chains of Selects October 29, 2008

Posted by reidmix in Code, Example, Javascript.
Tags: , , , , , ,
3 comments

I was looking for javascript library that would manage select (HTML) elements that are dependent on one another.  These are the drop-downs you often see on online car sites where you select a make and it populates the next drop-down with the models for that car make.

I was hoping that there would be a libary that was publically available, object oriented, small, backed by JSON, and would even like it to be based on the Prototype library.  All I could find was a library that may satisfy one of my requirements but not all.  Libraries I found were either procedural, terribly bulky and complicated, and never backed by JSON.

In my buy it or build it moment, I decided to build it: here is a chained_selects javascript library.  It’s fairly lightweight, it runs in about 85 lines (comments and whitespace included), you can initialize it with javascript objects or JSON, it’s object oriented and relies on just a little bit of Prototype.

You need the heirarchy of data to back a ChainedSelect object, the form, and selects that are assoicated with each “level” in the heirarchy.  It can have as many levels you want in the hierarchy from 2 up.  So, in my car example, imagine you have a two car makes (Acura and Volkswagen) and the Acura make has two models (the RL and the TL, sweet!), and the Volkswagen make has three models (Beetle, Jetta, and the Passat).  Each of the models have a database id.  My JSON for this heirarchy would look like:

var data = {"Acura":{"RL":1, "TL":2},"Volkswagen":{"Beetle":3,"Jetta":4,"Passat":5}}

You can see the first level is the outer-most hash with the makes, and the inner mosts hashes have the models and their db ids.  For rails programmers, this could be a rails hash that you run to_json with.

I set up my HTML form, with a select for each level in the heirarchy, like so:

  <form id="cars" method="post" action="/choose_car">
    <select name="make"></select>
    <select name="model"></select>
  </form>

Then I can setup the ChainedSelect object to manage these selects, using the data above:

new ChainedSelect(data, 'cars', ['make','model']);

This says, created a chained select with my data for the form with id ‘cars’, with the first level select with the name ‘make’ and second level select with the name ‘model’.

The first select will load with three elements:

  • Choose make…
  • Acura
  • Volkswagen

When Volkswagen is selected, the second select will load:

  • Choose model…
  • Beetle
  • Jetta
  • Passat

If Acura is then chose, the second select will refresh with the correct data. If the ‘model’ is chosen let’s say Jetta, then the id for that model is sent in the form (4).  For rails developers, the name of the select needs to be different from the label (“Choose model…”), you can specify a label and a select name separately, with an embedded array, like so:

new ChainedSelect(data, 'cars', ['make',['car[model]','model']]);

Oftentimes, we have an edit page with the values already prefilled on our forms, we can add another array parameter that specifies the path to the selection:

new ChainedSelect(data, 'cars', ['make','model'], ['Volkswagen','Jetta']);

Lastly, when the final select is chosen, sometimes we want to take an action or an AJAX call, we can supply an onComplete function to run which is yielded a the value chosen:

new ChainedSelect(data, 'cars', ['make','model'], null, function(choice) { alert("You chose:"+choice); } );

You can use all of these elements together to get the behavior you want, I also have a little rails form helper to create my javascript for me:

  def chained_selects(tree, form, selects, active, oncomplete=nil)
    %(new ChainedSelects(#{tree}, '#{form}', #{selects.inspect}, #{active.inspect}, #{oncomplete || 'null'});)
  end

I know that the script can be improved in many ways (Doug McInnes added the onComplete feature).  Please feel free to send patches or any bugs you may find.
Enjoy!