views:

47

answers:

2

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

A: 

You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.

Kronass
+1  A: 

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.

Marimuthu Madasamy
@Marimuthu: Thanks for your reply.How do i set the value outside the script tag. Example The following snippet are outside the <script> tag.<input type="hidden" name="userName" value="Administrator"/><c:set var="user" value=""/> // how do i set hidden variable value here (user variable)?
Thomman
The 'user' variable is a scoped attribute at server side and the input element is available at client side. To update something in server, you need to post the data to server through form submission. If you want to display some data from the server, you can do it as part of generating the response content as in my example. Moreover it doesn't matter for the container to execute a JSTL whether it is inside a script tag or not because it just parses the JSTL, executes and renders the resulting response(if any) from tag; It renders other texts(HTML/JavaScript) as it is.
Marimuthu Madasamy