Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the JSTL variable value in javascript?

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)?

like image 260
Isabel Jinson Avatar asked Jul 20 '10 04:07

Isabel Jinson


People also ask

Can we use JSTL in Javascript?

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.

How do you write if in JSTL?

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.

What is C set in JSTL?

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.


2 Answers

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.

like image 169
Marimuthu Madasamy Avatar answered Sep 30 '22 16:09

Marimuthu Madasamy


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

like image 24
Cyril Deba Avatar answered Sep 30 '22 18:09

Cyril Deba