Take the 2-minute tour ×

OK, I'm a javascript/grails novice and I'm not sure what to do here.

Basically I have a javascript function that is being called with multiple parameters and I want to substitute them into a grails parsable string.

I have a number of grails drop downs that call a javascript function to link to another page with multiple parameters that need to be passed (item number and quantity).

Here is the select:

<g:select optionKey="key" optionValue="value" value="${item.getQty()}" name="qty" from="[1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9]"

The javascript function:

<script type="text/javascript">
function goToPage(itemId, val){
window.location.href="${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}" + itemId + val;

So, it takes the itemId and val, concats them and replaces the last set of quotes with that concatenated value. What I want to happen is for each of the parameters to replace one of the sets of quotes.

I really don't understand how what looks like concatenating a string actually substitutes a value.


share|improve this question

1 Answer 1

up vote 1 down vote accepted

You're getting your server and client sides mixed up here. The


is evaluated by Grails on the server side when rendering the GSP into HTML, so what you end up with in your JavaScript will be something like

function goToPage(itemId, val){
  window.location.href="/myapp/GOrder/updateShoppingCart?item=&amp;qty=" + itemId + val;

What you probably want instead is to generate just the base URL up to the question mark on the Grails side, then add the query parameters on the client side in JavaScript

function goToPage(itemId, val){
         ).encodeAsJavaScript()}?item=" + encodeURIComponent(itemId)
    + "&amp;qty=" + encodeURIComponent(val);

Note the way I've added encodeAsJavaScript() - you should always use this when generating values that are to be included in a JavaScript string literal, it will backslash-escape anything that needs it. Similarly any JavaScript string you're adding to a URL needs to be encoded using the JavaScript encodeURIComponent function - if the value of itemId were "item one", for example, you need to append item%20one to the URL.

share|improve this answer
I had just figured out something similar, but good suggestion with the encoding! Thanks! –  clovold Nov 14 '12 at 14:45
i wonder a little on the encoded '&' in the url, but otherwise, that's the ticket. –  Brian Henry Nov 14 '12 at 14:47

Your Answer


