0

I have following code:

var n = 1;
var term = "${abc[n].term}";
console.log("term = " + term);

term seems to be empty, but if I replace var term = "${abc[n].term}"; by var term = "${abc[1].term}"; it works.

It looks like jsp is looking for the n property of the deck object, how could I fix it so that n is replaced by its value when I use is as array index ?

Edit: It seems that it's not a good idea to try mixing JSTL and Javascript, and that if you want to use a javascript variable as array index, you must copy the object to an Array object, like this:

var deck = new Array();
<c:forEach var="v" items="${abc}">
    deck.push("${v.term}");
</c:forEach>

var n = 1;
console.log("term = " + deck[n]);
1
  • You can perfectly mix JavaScript with JSP/JSTL/EL. You should only understand that JSP/JSTL/EL runs in webserver and produces HTML code and that JavaScript is part of the produced HTML code which in turn runs in webbrowser. Rightclick page in browser and do View Source. Do you see it now? You should write JSP/JSTL/EL code in such way that it produces exactly the desired HTML/JS code. Commented Jun 23, 2013 at 19:00

1 Answer 1

1

You are not using quotes properly, try this:

var term = "${abc[" + n +"].term}";

"${abc[n].term}" here n is considred as a part of the string not as your variable n. So try concatenating it.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, that's what I tried at first but I get the following exception if I do that :java.lang.NumberFormatException: For input string: " + n + " java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)java.lang.Integer.parseInt(Integer.java:481)
The ${...} in JSP is used to evaluate server-side variables. You seem to have completely missed that point.

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.