1

I have below line in my grails gsp file.

    <div class="pagination">
        <g:paginate total="${lotCount ?: 0}" />
    </div>

I want to pass lotCount value to one of my javascript named area-switcher.js file to further use it. How can I do this?

I tried to refer one suggestion from How to pass a value directly from a controller to a javascript file in Grails where I do below in my gsp

<g:javascript> var theId = ${lotCount} </g:javascript>

and try below in my js file for testing

alert(theId);

but it doesn't work. Got error like ReferenceError: theId is not defined. Please help.

2
  • start by putting speech marks around the id call so var theId = "${lotCount}"; Commented Mar 26, 2017 at 19:36
  • @vahid I still have the same error as theId is not defined Commented Mar 27, 2017 at 2:33

2 Answers 2

1

Use a hiddenField:

<g:hiddenField name="lotCount" value="${lotCount}" />

<div class="pagination">
    <g:paginate total="${lotCount ?: 0}" />
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Your solution should work.

Just ensure that in source of generated html page line

<g:javascript> var theId = ${lotCount} </g:javascript>

is placed before line which includes area-switcher.js

<script type="text/javascript" src="area-switcher.js">

Besides that, there are two more options to pass some value from .gsp to javascript file (examples use jQuery):

  1. By using of data attribute. For example,

gsp (here div, span, input, other tags could be used):

<div id="countElem" data-count="${count}">

js(jQuery used here):

var count = $("#countElem").data('count');
  1. As was mentioned in another comments, by using of hidden field:

gsp:

<g:hiddenField name="countElem" data-count="${count}"/>

js(jQuery used here):

// hidden field will have name and id equals to countElem
var count =  $("#countElem").val();    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.