Link to home
Start Free TrialLog in
Avatar of leon24
leon24

asked on

Convert Java variable to Javascript variable

Hi guys,

This is pretty weird. I'm using BEA workshop 8.1. In my JSP, there is a Javascript which I need to convert a Java variable to Javascript variable.

A section of my codes goes below:

<%
String hsCode = request.getAttribute("hsCode");
System.out.println(hsCode);
%>
var JShsCode = <%=hsCode%>;
alert(JShsCode);

In my console, the hsCode is printed out as 0701, but in my alert box when I load the JSP, JShsCode becomes 449. With each different value of hsCode, the JShsCode value changes .e.g. hsCode 077 will alert me JShsCode 63.

Any ideas on this?

ASKER CERTIFIED SOLUTION
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh. The trigger for an octal number is a leading 0.

You could also left trim all leading zeros.

Not sure on the Java method for that.

You could just read 1 char at a time and convert to a space and then not put the quotes in the JS output.

So, (using _ as a space), 0701 ...

var JShsCode = 0701;

becomes (remember using _ as a space) ...

var JShsCode = _701;


Which removes the octal notation marker.
Personally, I would output the correct value from the server rather than getting the client to do the call.
Avatar of leon24
leon24

ASKER

Hi guys,

I've tried using the methods mentioned, I've missed this part out earlier in my question. The hsCode 0701 is a number which the user input, which means it could be 334 or 0802 or 0701 or anything (numeric). And I tried using parseInt, but it doesnt retain the 0 in front, as code 0701 is different from 701.

Any idea?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of leon24

ASKER

OK guys I've solved it oredi and using '<%=hsCode%>' works fine and retains the leading 0 in front. You guys are cool s**t!
Well, we are Experts anyway!