How to pass java string variable to the javascript function by jsp expression tag?
Solution 1
Try using single quote '
when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
Solution 2
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'
.
You should add the '
chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \"
to escape as this would break your code.
Aditya
Updated on July 18, 2022Comments
-
Aditya almost 2 years
I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script> function stringGenerate(str){ var x = document.getElementsByTagName("input"); x[0].value = str; } function numberGenerate(num){ var x = document.getElementsByTagName("input"); x[1].value = num; } </script> </head> <body> <% String num ="1234567890"; String str = "abcdefghij"; %> <input type="text" name="string" readonly="readonly"/> <input type="text" name="number" readonly="readonly"/><br/><br/> <input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" /> <input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" /> </body> </html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
-
Aditya about 9 yearsThanks a lot...it's run properly.