user1471159
user1471159

Reputation:

set value of jquery variable equal to a jstl variable

I have a jstl value,

<c:forEach items="${detail}" var="u">
<c:set value="${u.content}" var="c"/></c:forEach>

I want to set the variable in jquery equal to the var = "c".

How could I do that?

Upvotes: 0

Views: 5971

Answers (2)

kakabali
kakabali

Reputation: 4033

the method given in the below code might be correct but the variable whatever would have only one value that also only during the last count of the for each loop would exist

<script>
    <c:forEach items="${detail}" var="u">
        <c:set value="${u.content}" var="c"/>
        var whatever = ${c};
    </c:forEach>
<script>

for instance if the loop for the variable detail is of list type that consists of string type objects in it like "A" , "B" ,"C" then in the case the value of the var whatever will be "C", this is because jstl is compile time language.

So the above code won't work in for each loop the following code might help you out or atleast provide you a idea for same.

<script>
    var whatever = new Array;
    <c:forEach items="${detail}" var="u">
        <c:set value="${u.content}" var="c"/>
        for (var i=0;i<whatever.length;i++)
        {
            whatever[i]=${c};
        }
    </c:forEach>
<script>

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160261

<script>
  <c:forEach items="${detail}" var="u">
    <c:set value="${u.content}" var="c"/>
    var whatever = ${c};
  </c:forEach>
<script>

You might need to JS escape it, quote it, etc. depending on what's actually in the variable, which you don't mention. It's also not clear what "a variable in jQuery" is.

The bottom line is that if the JavaScript lives in a JSP, just use the value: the JS isn't evaluated until the response has been emitted, so mix-and-match, but be aware that it's pretty easy to create invalid JavaScript unless you take care to properly escape whatever value types you're emitting.

As an example, consider a Java String that contains a single quote: if you single-quote the Java value in JS you'd have invalid JS because you didn't JS-escape the string value.

Upvotes: 2

Related Questions