Reputation: 15
I have two events, I didn't get what's wrong here both are executed, i.e. if the change
occurs, the click
is also executed.
As other option, is it possible to use <c:choose>...</c:choose>
for multiple events?
Thank you!
<script>
$(document).ready(function () {
$('#idSelect').change(function (){
<c:set var="messjSelect" value="10" scope="session"/>;
<c:set var="messjRefresh" value="0" scope="session"/>;
});
});
</script>
<script>
$(document).ready(function () {
$('#refreshButton').click(function () {
<c:set var="messjRefresh" value="0" scope="session"/>;
<c:set var="messjSelect" value="0" scope="session"/>;
alert("do iT! ${messjSelect}");
});
});
</script>
Upvotes: 0
Views: 88
Reputation: 2725
Both are executed because you're mixing server side technology with front end technologies.
Before your server sends the client the jsp file it looks for any java related code and runs it. This means that the JSTL/EL you have in your jsp page will run before your html/css/js.
So to clarify, the <c:set
tags you have there both run because it's server side technology. It doesn't matter if you specify within javascript to only run after a click. It will run anyway. JSTL/EL and javascript don't work together in the way you think they seem to work.
How can you fix this?
One possible solution is to send an AJAX request to a servlet. And in that servlet you handle the session variable then return whatever you want to. For example:
<script>
$(document).ready(function () {
$('#idSelect').change(function (){
$.post("../SelectChangeServlet");
});
});
</script>
<script>
$(document).ready(function () {
$('#refreshButton').click(function () {
$.post("../RefreshButtonServlet", function(response) {
alert("do iT: "+ response);
});
});
});
</script>
SelectChangeServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = (request.getSession()); //get session
int messjSelect = 10;
int messjRefresh = 0;
session.setAttribute("messjRefresh", messjRefresh);
session.setAttribute("messjSelect", messjSelect);
System.out.println("You will see this text in IDE console when #idSelect is changed");
}
RefreshButtonServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = (request.getSession()); //get session
int messjSelect = 0;
int messjRefresh = 0;
session.setAttribute("messjRefresh", messjRefresh);
session.setAttribute("messjSelect", messjSelect);
System.out.println("You will see this text in IDE console when button is clicked");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(Integer.toString(messjSelect)); //return messjSelect for alert (needs to be a string)
}
More info on Ajax with Servlets here: How to use Servlets and Ajax?
Upvotes: 1