0

I have an issue with a parameter that I'm trying to pass into a Javascript function where the parameter gets cut off.

In my Servlet, I have set a parameter request.setAttribute("questions", service.getQuestions("123"))

It sets a list of questions with each question containing several values;

I loop through them with a JSTL loop <c:forEach var="data" items="${questions}">...</c:forEach> which I can then access the values as so ${data.question}, ${data.options} etc.

console.log(${data.question}) returns a value of the form 123,45,35|43,94,73|23,91,34 which is as expected.

But when I try to pass this ${data.question} into a javascript function such as <script>MyFunction(${data.question})</script>, it only receives 123.

MyFunction(data) {
    console.log(data); //Only shows 123
    //Split the string into arrays for processing
}
Jack
  • 5,680
  • 10
  • 49
  • 74
  • Beacause it returns the first element from the array – Santhosh Apr 03 '14 at 06:28
  • @sankrish It's a string, not an array. – Jack Apr 03 '14 at 06:47
  • `${data.question}` outside the `for-each` loop will hold the value for the current iteration alone – Santhosh Apr 03 '14 at 06:53
  • `${data.question}` is a string `123,45,35|43,94,73|23,91,34`, not an array. The loop is to loop through the list `questions`. `questions` contains several objects that have the attribute `question`, `options`, and others. – Jack Apr 03 '14 at 07:32

1 Answers1

2

You receive first element becouse your function expect one parameter, and your value 123,45,35|43,94,73|23,91,34 is split by comma so it looks for function like diferent parametrs. Use arguments property insted or pass all value as string in '' like this

<script>MyFunction('${data.question}')</script>

Sorry for my english.. still working on it

Łukasz Szewczak
  • 1,851
  • 1
  • 13
  • 14
  • I see, it was being passed as `MyFunction(123, 45, ...)` instead of `MyFunction("123,45,...")` – Jack Apr 03 '14 at 23:50
  • Don't forget to escape it! See [How to escape JavaScript in JSP?](https://stackoverflow.com/questions/9708242/how-to-escape-javascript-in-jsp) `` – David Balažic Aug 08 '17 at 11:33