Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an EL variable to javascript

Tags:

javascript

jsp

el

I have a variable ${bean.name} how can i pass it to a javascript var? I've tried var name = "${bean.name}" and var name = ${bean.name} but it does not work.

my idea is to put it in a hidden input like in a hidden <input id="test" type="text" value"${bean.name}">

var name = document.getElementById("test").value;

this doen't work either var name becomes the string "${bean.name}"

note. i can't use jstl

like image 914
Dave819 Avatar asked Mar 14 '26 14:03

Dave819


2 Answers

You can't have JSTL evaluated in .js files. Only in .jsp files. (unless you remap the jsp servlet, but I wouldn't advise to do so).

The better approach is to define the variables in the .jsp including the .js, and pass these variables as arguments to an initializing function.

Also make sure you don't have isELIgnored="true"

like image 172
Bozho Avatar answered Mar 16 '26 03:03

Bozho


this doen't work either var name becomes the string "${bean.name}"

Make sure that you're running a Servlet 2.4 capable container and that web.xml is declared as Servlet 2.4 or higher.

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <!-- Config here. -->

</web-app>

This way EL will work in template text as well (without the need for JSTL <c:out>). It was namely introduced in Servlet 2.4 / JSP 2.0. Tomcat 5.5 is an example of a Servlet 2.4 container. If your container supports a higher servlet API version, e.g. 2.5 or 3.0, then you should declare the web.xml conform this version to benefit all newest features.

You'll then also be able to do the following in the JSP:

<script type="text/javascript">var name = '${bean.name}';</script>
like image 23
BalusC Avatar answered Mar 16 '26 04:03

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!