Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP : using java variable in Javascript [duplicate]

I have a JSP page called index.jsp. I have a Java variable called totalCount inside this page :

<%= int totalCount = getTotalCount();%>

Now I want to use this variable in Javascript section to generate a chart:

<script type="text/javascript">
</script>

How can I pass this Java variable inside ? Thanks.

like image 795
hawarden_ Avatar asked Jan 29 '26 12:01

hawarden_


2 Answers

Just assign the value to your Javascript variable.

<script type="text/javascript">
var count = '<%= totalCount %>';
</script>

But using scriptlets been highly discouraged and shift to JSTL as soon as possible.

Read : How to avoid Java code in JSP files?

As others pointed out, do not create unnecessary hidden elements on DOM. If you really want to use this variable across files declare this variable on top. Even before script includes, so that it avail across all the files.

Example:

 <script type="text/javascript">
    var count = '<%= totalCount %>';
    </script>
<script type='text/javascript' src='js/blah.js'></script>     
<script type='text/javascript' src='js/blahblah.js'></script>     
like image 179
Suresh Atta Avatar answered Feb 01 '26 00:02

Suresh Atta


Just create a hidden field on your HTML page and access that value using JavaScript.

HTML

 <input id='hdn-total-count' type='hidden' value='<%=totalCount%>' />

JavaScript

 var totalCount = document.getElementById('hdn-total-count').value;

jQuery (Cross browser compatible)

 var totalCount = $('#hdn-total-count').val();

All of the other answers are going to work on inline and on-page JavaScript. But they are not going to work for JavaScript in external files (which are cacheable).

like image 40
Allan Chua Avatar answered Feb 01 '26 02:02

Allan Chua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!