views:

873

answers:

2

Hi all, in my jsp page I have:

<form:select path="index" id="sIndex" onchange="showDetails()">
    <form:options items="${smth}" itemLabel="name" itemValue="index"/>
</form:select>

And in my javascript function:

 *function showDetails() {
        var sIndex=document.getElementById("sIndex");
        var index=sIndex[sIndex.selectedIndex].value;
        var name = '${smth[index].name}';
        var address = '${smth[index].address}';
        var message = "<table><tr><td>Name:</td><td>" + name + "</td></tr>";
        message = message + "<tr><td>Address:</td><td>" + address + "</td></tr>"
        message = message + "</table>"
        document.getElementById("candDetails").innerHTML = message;
    }*

And it doesn't takes the index in ${}, but if I use alert(index) it recognize it. Thanks in advanced

+3  A: 

Java/JSP/JSTL runs at the server side, produces HTML/CSS/JS output and sends it to the client. HTML/CSS/JS runs at the client side, not at the server side as you apparently expected. Open the page in your browser and do a 'view source'. Do you see it?

Javascript only sees the HTML DOM tree in the client side and can access it. You need to get the name and address from the HTML DOM tree. You already have the name in the option element, but the address is nowhere available. You could use JSTL to generate a Javascript array variable so that the Javascript code can use it further.

To learn more about the wall between Java/JSP and Javascript you may find this article useful.

BalusC
Hi, thanks for your reply, the article was very useful. I tried to generate array variable but I can't get it to work ( I receive: 'According to TLD or attribute directive in tag file, attribute items does not accept any expressions'). Have any suggestions?Thanks
This is a different problem which probably needs its own topic. This problem indicate a version conflict. At least you need to check and align the JSTL/JSP/Servlet versions. Minimum would be Servlet 2.4/JSP 2.0 (e.g. Tomcat 5.x) and JSTL 1.1. Better is to get the newer Servlet 2.5/JSP 2.1 (e.g. Tomcat 6.x) and JSTL 1.2.
BalusC
A: 

The EL expressions (the code between ${}) are evaluated at runtime of the JSP servlet, not once the page has been rendered in the browser, which is when your JavaScript is being called.

View the generated source of the page and you will probably see the problem.

cjstehno