How to set the JSTL variable value in java script?
<script> function function1() { var val1 = document.getElementById('userName').value; <c:set var="user" value=""/> // how do i set val1 here? } </script>
How do I set the 'user' variable (JSTL) value from 'val1' (Java script)?
The JSTL fn:escapeXml() function is useless when you're interpolating a JSP variable into a part of the page that will be interpreted as Javascript source by the browser. You can either use a JSON library to encode your strings, or you can write your own EL function to do it.
The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated is true. It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.
JSTL Core Tags c:set allows to set the result of an expression in a variable within a given scope. Using this tag helps to set the property of 'JavaBean' and the values of the 'java.
It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.
var val1 = document.getElementById('userName').value; <c:set var="user" value=""/> // how do i set val1 here?
Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.
Now for example,
<script type="text/javascript"> <c:set var="message" value="Hello"/> var message = '<c:out value="${message}"/>'; </script>
Now for the browser, this content is rendered,
<script type="text/javascript"> var message = 'Hello'; </script>
Hope this helps.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With