0

In the code below, I am trying to use the var i in the java method option.value = <% ppList.get(i).getId(); %> but it is not working out for me very well.

here is the full js function:

function receiveAnswer(response) {
  var aSeats = document.getElementById("aSeats");
  while (aSeats.childNodes.length > 0) { // clear it out
    aSeats.removeChild(aSeats.childNodes[0]);
  }
  <% List<Physical_Package> ppList = (List<Physical_Package>) session.getAttribute("currentPack"); %>
  for (var i = 0; i < response.aSeats.length; i++) { // add the items back in
    var option = aSeats.appendChild(document.createElement("option"));
    option.setAttribute("type", "hidden");
    option.setAttribute("name", "id");
    option.setAttribute("value", "")
    option.appendChild(document.createTextNode(response.aSeats[i]));
    option.value = <% ppList.get(i).getId(); %>
  }
}
novicePrgrmr
  • 18,647
  • 31
  • 81
  • 103

1 Answers1

2

You're mixing two entirely different things here. The Java code runs on the server and the resulting page containing the JavaScript is sent to the browser. i is a JavaScript variable and does not exist when the Java code is being executed.

One solution is to print out all the IDs in ppList into a JavaScript array, which you can then access from the client-side:

var array = [
<%
  List<Physical_Package> ppList = (List<Physical_Package>) session.getAttribute("currentPack");
  for (Physical_Package pp : ppList)
    out.println(pp.getId() + ",");
%>
];
...
option.value = array[i];

This is just an example; it is bad practice to intermingle Java code in your JSP files. Consider using JSTL or one of the alternate solutions described here: How to avoid Java Code in JSP-Files?

Community
  • 1
  • 1
casablanca
  • 69,683
  • 7
  • 133
  • 150