1

Possible Duplicate:
JSP Variable Accessing in JavaScript

I have a java variable and a javascript on a jsp page.

<% int max=70; %>

How do I get the variable from the script?

var x = ???

I tried document.getElementById() but unfortunately it didn't seem to work as it isn't a html element

this is my error:

Unable to compile class for JSP:

An error occurred at line: 13 in the jsp file: /search.jsp
max cannot be resolved
10:     function validateForm() {
11:         var x=document.forms["search"]["capacity"].value;
12:         var y=document.forms["search"]["date"].value;
13:         var m=<%=max%>;
14:         if (isNaN(x)) {
15:             alert("Capacity must be an Integer");
16:             return false;
Community
  • 1
  • 1

1 Answers1

6

JSP is a HTML code producer. JS is part of HTML.

Just let JSP print JS variable accordingly.

var x = <%=max%>;

Open page in browser, rightclick and View Source to verify if JSP-generated HTML/JS syntax is proper.

See also:


Unrelated to the concrete problem, using scriptlets is considered discouraged since a decade. To learn about the right ways, carefully read How to avoid Java code in JSP files? Assuming that max is available in the EL scope, you could print it as follows:

var x = ${max};
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • this is my error Unable to compile class for JSP: An error occurred at line: 13 in the jsp file: /search.jsp max cannot be resolved 10: function validateForm() { 11: var x=document.forms["search"]["capacity"].value; 12: var y=document.forms["search"]["date"].value; 13: var m=<%=max%>; 14: if (isNaN(x)) { 15: alert("Capacity must be an Integer"); 16: return false; – Jackson Siah Wei Qiang Oct 12 '12 at 11:30
  • That just means that `max` is nowhere been declared in the same scope. Are you sure that you've a `<% int max=70; %>` in the same scope? For example, if it's in a different JSP page or in a method declaration then it obviously won't work (exactly like as in normal Java classes). – BalusC Oct 12 '12 at 11:32