6

I'm using a g:select (actually, a g:currencySelect) in my view.

I want a controller action to fire as soon as the user changes the value in the resulting select box.

How can I do this?

Dick Chesterwood
  • 2,425
  • 2
  • 23
  • 32

3 Answers3

10

I think I'm answering my own question here, but do let me know if there's a better way of doing this:

Use the onchange javascript function in the select tag:

<g:form controller="changeCurrency" action="changeCurrency">
    <g:select onchange="submit()"/>
</g:form>
Dick Chesterwood
  • 2,425
  • 2
  • 23
  • 32
  • This fails to work for me assuming I don't have to define what submit() does. – Salvador Valencia Oct 01 '14 at 19:14
  • submit() will submit the form. You don't define submit(), but you will need a corresponding controller to handle the submission, in this example there will be a ChangeCurrencyController with an action called changeCurrency(). – Dick Chesterwood Oct 01 '14 at 19:56
  • Sorry you were right, submit() works if there is nothing else in your form using the name "submit". I found my bug with help from this http://stackoverflow.com/questions/833032/submit-is-not-a-function-in-javascript – Salvador Valencia Oct 01 '14 at 20:42
  • What if I want to call a different controller method for submit as opposed to a onChange? – Sai Mar 29 '16 at 04:42
4

In case you want an ajax request, try this:

<g:select name="type" from="${['import-a', 'import-b']}"
onchange="jQuery('#addArea').load('/app/import/chooseImportType/' +
jQuery('#type').val())"/>

In controller:

def chooseImportType (){
 render params.id
}

Worked in Grails 2.0.4

Mohamad
  • 41
  • 1
4

Another way can be:


    <g:select name="someName" from="${list}" onchange="goToPage(this.value)"/>

    <script type="text/javascript">

    function goToPage(requestParams){
    window.location.href="${createLink(controller:'controllerName' ,action:'actionName' ,params:[paramsName:""])}" + requestParams;
    }

    </script>