Using jQuery and Grails to create chained selects / drop-downs

In web application development, use of frameworks has become essential . One of those frameworks which help us in making things simpler and life easy is jQuery.

Why jQuery ?

  • Fully Documented
  • Great Community
  • Tons of plugins
  • Small size(14kb)
  • Everything works in IE 6+,Firefox,Safari 2+,and Opera 9+

jQquery is a very efficient framework which helps us in developing many things in a much easier way than they would be without using any framework.

At IntelliGrape we are using Grails and jQuery on a project.

In this blog, I want to share one of my experiences that I had met in this course of time. A series of mails/questions in Grails mailing list on creating chained selects/drop-downs prompted me to write this blog; since I had already done this.

Chain select basically means populating the next drop-down on the basis of what you select in the present drop-down.

In this example, we have two drop-downs – manufacturer and model. We want the model drop-down to be populated on the basis of what the user selects in the manufacturer drop-down, without doing a full page refresh, using an Ajax call.

Here are my classes, not the whole class but a part of the class

Vehicle Class

public  class Vehicle {
  Manufacturer manufacturer
  Model model
}

The Manufacturer and model classes look like this

Manufacturer Class

public class Manufacturer {
  String manufacturerName
  static belongsTo = Vehicle
  static hasMany = [models: Model]
}

Model Class

public class Model {
  String modelName
  static belongsTo = Manufacturer
}

For this the vehicleCreate.gsp should look like this /vehicle/create.gsp

            Home
            Vehicle List

Create Vehicle


${flash.message}
<table>
<tbody>
<tr>
<td valign="top"><label for="vehicleName">Vehicle Name:</label></td>
<td valign="top"></td>
</tr>
<tr>
<td valign="top"><label for="vehicleManufacturer">Manufacturer</label></td>
<td valign="top"><g:select id="vehicleManufacturerDropDown" optionKey="id"
                                     from="${VehicleManufacturer.list()}"
                                     name="vehicleManufacturerDropDown" value=""/></td>
</tr>
<tr>
<td valign="top"><label for="model">Model</label></td>
<td valign="top"><g:select id="model" optionKey="id"
                                       from="${VehicleModel.list()}"
                                       name="model" value=""/></td>
</tr>
</tbody>
</table>

$(document).ready(function() {
      $("#vehicleManufacturerDropDown").change(function() {
      $.ajax({
              url: "/ChainDropDown/vehicle/manufacturerSelected",
              data: "id=" + this.value,
              cache: false,
              success: function(html) {
              $("#models").html(html);
              }
            });
         });
       });
 Now we will look at how this chained selection works using jQuery.Now what all we are left-out with is
handling this event in the VehicleController which is as simple as any other controller action.
Just add manufacturerSelected action in the controller and we are done!

VehicleController
class VehicleController {
  def manufacturerSelected = {
    def manufacturer = VehicleManufacturer.findById(params.id)
    render g.select(optionKey: 'id', from: manufacturer.models, id: 'model', name: "model")
  }
}

You can download the complete source code for a working sample app with the examples used in this blog. Hope this helps somebody. Pradeep Garikipati

12 thoughts on “Using jQuery and Grails to create chained selects / drop-downs

  1. Thanks, for the post. I need to do something exactly like this and you posted a solution.

    I am looking forward to giving it a try.

    Jim Shingler

  2. This is really nice – thanks.

    To make the example complete, when the page is first loaded, the #models should be populated for whatever manufacturer happens to be pre-selected.

    Unless the user changes the manufacturer, the list of models will be wrong.

  3. GSP or g tags are used to embed jquery or make forms say i donot want to use GSP completely, like completely coded in HTML, CSS and Javascript, call through http request from javascript to get the resource in json and interpret and display that.

    Will this sort of architecture work?

    Regards,
    sr

  4. Pingback: asp.net, c#,javascript

  5. sir, could please provide sample programs on jquery while we are using graisl frame work software. if avaialble could please send me the url’s atleast………………..

  6. I want to get the values from the same database table for multiple dropdowns could anyone please help me out..

    I have three drop downs two dependent on one and three dependent on two and all the three values are in the same table

    How to get the values from the same table with the same instance

  7. Thanks for the tutorial. Fairly simple and straight forward to follow. Much appreciated and is one of the best explanations I’ve seen so far with regards to Grails.

  8. Thanks for this example. It is the best example of how all the pieces and parts fit, and where to put them that I have found. 1 questions however, (and I am very new at grails / jquery / ajax). I don’t see how chains.js ever gets called. Any chance you could give me a hint? Thanks.

  9. Thank you so much for posting this. As others have said this is the most helpful example of doing this in grails. It’s really helped me to understand the syntax of ajax calls.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>