I’ve never been much of a Javascript fan, but thanks to jQuery, I find myself actually enjoying the times when Javascript is needed. This is nothing against Prototype, the jQuery syntax just clicks with me.
As Rails is coupled with Prototype pretty well, I didn’t want to do a complete switch with something like JRails, I wanted to mix it in… get the best of both worlds.
So, I made use of the jQuery.noConflict(); functionality and started using jQuery. My first was use was with the very nice Treeview plugin. I really like this plugin.
As I don’t like to code for purely academic purposes, I didn’t do much else with jQuery until I found a need to use an observe_field (Rails helper name) type functionality (Prototype type just calls this method “observe”). The basic idea was that I have a select input with various task types. On the “on_change” event, I wanted go to the new task page passing the task_type_id I wanted to create.
So, here’s the jQuery way to do this:
jQuery("#task_type_id").bind("change",function(){
location.href = "/projects/<%= @project.id %>/tasks/new?task_type_id=" + jQuery(this).val();
To break this down a little:
My select tag has an id of “task_type_id”, this part finds and returns the select element.
jQuery("#task_type_id")
Now I want to bind an event to the select element. The first parameter of the bind call is the type of event you want to bind to:
.bind("change"
The second parameter to the bind call is the function you want executed when this event fires:
function(){
location.href = "/projects/<%= @project.id %>/tasks/new?task_type_id=" + jQuery(this).val();
}
This gets the value of the select element to pass into the location.href call:
jQuery(this).val()
So now when my select box value is changed, the user is sent to the new task page with the appropriate task_type_id.
