问题描述:

How do you get a value from Expression Language (EL) in a JSP to a JavaScript function?

In my JSP page I have:

<li>${state}</li>

<input title="Show ${state}">Show</>

And I would like to be able to get the ${state} from the JSP into the JavaScript function:

$('#input').click(function() {

if ($(this).val() == "Show + ${state}">")

{

$(this).val("Show");

$(this).attr("title", "Hide + ${state}"> ");

}

else

{

$(this).val("Hide");

$(this).attr("title", "Hide + ${state}">");

}

});

I want for the title of each button to say show Ohio or Hide Ohio, but to change for whatever state is in the <li> tag.

网友答案:

That JavaScript has to go in a <script> inside a .jsp file instead of a .js file in order to get JSP to inline the EL variables.

Alternatively, you can also just do a simple string-replace of the first word or a substring of the first four characters. This way you don't need any EL in the JavaScript and thus you can just put the JS code in its own .js file.

By the way, the logic flow of your whole function makes at its own very little sense. Don't you actually want to check if the val() is "Hide"? Don't you actually want to use "Show" in the title of one of the two conditions?

网友答案:

If your possible values are going to be Show ${State} and Hide ${State} then you really only care about the first four characters:

if ($(this).val().substring(0, 4) == "Show")
{
    ...
}
...
相关阅读:
Top