Skip to content Skip to sidebar Skip to footer

Grails Chain Selects Without Domains

I'm trying to chain two, possibly three statements together using Ajax like is shown here Populate dropdown list using ajax In grails but all the examples I fi

Solution 1:

You can really do it without being javascript-library specific. If you use the grails built-in remoteFunction it will handle the jQuery portion for you. What you would then want for your degreeSubject select is:

<g:select name="degreeSubject" 
          from="${majors}" 
          noSelection="${['':'-Choose Subject-']}" 
          value="${degreeInstance?.degreeSubject }"
          onChange="${remoteFunction(
            controller: 'yourControllerName', 
            action: 'updateSelect', 
            params: '\'value=\' + escape(this.value),
            onSuccess: 'updateConcentration(data)')}/>

The key being the onChange event calling the remoteFunction. The remote function will make an ajax call to whatever controller action you want, but you'll need to call a javascript function to take in the results of your controller action and populate the other select. If you wanted to do this with simple js you could do this:

function updateConcentration(items) {
    var control = document.getElementById('degreeConcentration')

    // Clear all previous optionsvar i = control.length
    while (i > 0) {
        i--
        control.remove(i)
    }

    // Rebuild the selectfor (i=0; i < items.length; i++) {
        var optItem = items[i]
        var opt = document.createElement('option');
        opt.text = optItem.value
        opt.value = optItem.id
        try {
                control.add(opt, null) // doesn't work in IE
        }
        catch(ex) {
                control.add(opt) // IE only
        }
    }
}

and finally your controller action should look like this:

def updateSelect(value) = {
    def concentrations = degreeService.getConcentrations(value)
    render concentrations as JSON // or use respond concentrations if you upgrade to 2.3
}

Post a Comment for "Grails Chain Selects Without Domains"