Last updated by Vahid 3 years ago


A common pattern that pops up in Web development is the need to have one SELECT box change the contents of another SELECT box on the same page without doing a refresh.

Take the following domains as an example:

class Country {
    String name
    String abbr
    String language

static hasMany = [cities:City] }

class City { String name String timezone

static belongsTo = [country:Country] }

On our web page, we want to constrain the user to entering only Countries and Cities that our database knows about. This is a perfect use for SELECTs on our webpage. However, because City belongs to Country, we will need to change the City SELECT when the user change's the Country SELECT. Once-upon-a-time we'd either just reload the entire page in response to ONCHANGE events in the Country SELECT or we'd preload all the countries and cities into the page in Javascript.

However, a modern web page can leverage AJAX and JSON to quickly and efficiently update the City select.

First, in the CountryController, add the following handler:

import grails.converters.*

class CountryController {

def ajaxGetCities = { def country = Country.get( render country?.cities as JSON } }

Remember to import the converters!

You can test your AJAX call using curl from the command line:

$ curl "http://localhost:8080/widgetco/country/ajaxGetCities/1

"[ {"id":4,"class":"City","country":1,"name":"Dallas","timezone":"CST"}, {"id":1,"class":"City","country":1,"name":"New York","timezone":"EST"} ]"

That was the easy part.

Next, you need to wire up your SELECTs in a GSP page. Things get a little more complicated. You'll be using a AJAX library in your GSP page, so first you must include that in your page's HEAD element, eg:

<g:javascript library="prototype" />

Next, you'll need a form with the SELECTs:

        optionKey="id" optionValue="name" name="" id="" from="${Country.list()}"
            params:'\\'id=\\' + escape(this.value)', 
    <g:select name="city" id="city"></g:select>
Where the 2 \ should be replaced by 1 \ (due to wiki syntax)
If you need to pass more than 1 parameter, use the character & :

params:'\\'id=\\' + escape(this.value)+\\'&id2=\\' + escape(this.value)'

In Grails 2 where JQuery is used by default, the return value is named "data" and you should to use "onSuccess" instead of "onComplete" method. "onSuccess" is a little bit easier to deal and there is no need to do an "eval()" on "data" object. If you intend to use "onComplete" method, then you can use "XMLHttpRequest" or/and "textStatus" as parameters. If you want do work with what the server returned to you, "XMLHttpRequest" (object) is the right choice, but if you just wanna know the text response ("error", "success", "timeout", etc), then use "textStatus" (string).

//The easiest way:
//Warrior way:
onComplete: 'updateCity(XMLHttpRequest)'
//Kuririn way: only text status:
onComplete: 'updateCity(textStatus)'
//Goku way: if we had two parameters, we also could do:
onComplete: 'updateCity(XMLHttpRequest,textStatus)'


  • If you use "onSuccess" method, use the "data" object.
  • If you use "onComplete" method, you can use "XMLHttpRequest" or/and "textStatus"
The above GSP creates a simple form with two SELECTs and preloads the SELECT from the database.

To complete the wiring, you need to write some Javascript:


function updateCity(e) { // The response comes back as a bunch-o-JSON var cities = eval("(" + e.responseText + ")") // evaluate JSON

if (cities) { var rselect = document.getElementById('city')

// Clear all previous options var l = rselect.length

while (l > 0) { l-- rselect.remove(l) }

// Rebuild the select for (var i=0; i < cities.length; i++) { var city = cities[i] var opt = document.createElement('option'); opt.text = opt.value = try { rselect.add(opt, null) // standards compliant; doesn't work in IE } catch(ex) { rselect.add(opt) // IE only } } } }

// This is called when the page loads to initialize city var zselect = document.getElementById('') var zopt = zselect.options[zselect.selectedIndex] ${remoteFunction(controller:"country", action:"ajaxGetCities", params:"'id=' + zopt.value", onComplete:"updateCity(e)")}


The above Code is for Grails 1.x where prototype is used. In Grails 2 with JQuery this has to be a bit different, especially the eval(...) is not necessary. "data" is a valid javascript object.

Everything is wired up now. When you change the SELECT, it will make an AJAX call to your Country controller. When the call completes, updateCity() will execute on your page, it being passed the block of JSON returned from your controller. The function evaluates the JSON and rebuilds the city SELECT.

One final bit of code at the bottom of the page initializes the city SELECT to match the SELECT when the page is loaded.

You can download the working demo from Dropbox.

There is a small typo in this example code:

<title>Demo of Selects</time>
should be
<title>Demo of Selects</title>
Also, adding
"/" (controller: 'country', action: 'selectdemo')
to the UrlMappings.groovy file allowed the index page to load properly.

Also check out this plugin.