Reading a jstl variable in javascript code.
Solution 1
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).
Solution 2
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;
Solution 3
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.
-
In the HTML code have a paragraph with the required variable.
<p id = "var" disabled = "disabled">${variable}</p>
-
Access the variable using
.innerHTML
inside the JavaScript function.function myFunction() { var jstl_var = document.getElementById("var").innerHTML; }
webExplorer
Updated on July 09, 2022Comments
-
webExplorer almost 2 years
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} });
-
vmtrue over 6 yearsPlease, use formatting because reading code is very difficult without formatting. stackoverflow.com/editing-help