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;
0

1 Answer 1

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};
Sign up to request clarification or add additional context in comments.

2 Comments

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;
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.