5

I want to read a jstl variable in a javascript function.

JS code submits a form.

$("#userSubmit").on('submit', function () {
    document.getElementById("userForm").submit();
});

So in server code -

request.setAttribute("userId", 435);

and after the page is loaded -> in the javascript code -

$("#textBoxInp").keyup(function() {
    // I want to access the userId here. 
    // in html code i can acccess it using JSTL syntax ${userId}
});
webExplorer
  • 1,025
  • 2
  • 17
  • 33

4 Answers4

12

Just write the Expression Language directly in your JavaScript code:

$("#textBoxInp").keyup(function() {
    var userId = '${userId}';
});

Note that this won't work if the JavaScript code is placed in a external file and is invoked in the JSP. In this case, you may refer to one of the four ways that BalusC explain here: Mixing JSF EL in a Javascript file (he explains five, but one of them is JSF specific).

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
8

One way is as suggested by Mendoza, but it will not work in case of having separate Javascript file.

in that case, another way is adding hidden field in JSP page, and reading same from Javascript.

JSP code:

<input type="hidden" id="xID" name="x" value="${myAttribute}"> 

JS code:

var myAtt = document.getElementById("xID").value;
user3657302
  • 347
  • 1
  • 5
1

If you want to access jstl variable in a javascript script function, you won't be able to access them directly. Here's a roundabout way(easy to implement) to do it.

  1. In the HTML code have a paragraph with the required variable.

         <p id = "var" disabled = "disabled">${variable}</p>
    
  2. Access the variable using .innerHTML inside the JavaScript function.

    function myFunction() {  
        var jstl_var = document.getElementById("var").innerHTML;
    
    }
    
Community
  • 1
  • 1
swethaesp
  • 11
  • 3
  • Please, use formatting because reading code is very difficult without formatting. https://stackoverflow.com/editing-help – vmtrue Nov 09 '17 at 12:31
0

totalClients is jstl variable and to read in javascript block please see below

<script type="text/javascript">

    $(document).ready(function() {
        var tc = "<c:out value='${totalClients}'/>";
    });
Draken
  • 3,134
  • 13
  • 34
  • 54
Anil Jain
  • 57
  • 3