0

I am building a JSP page that contains several IF statements when checking the data being loaded. I would like to call a jQuery function if one of those IF statements renders true. Is this possible?

example:

<c:if test="${!setvariable}">
     $(function(){
          //execute code here;
     });
</c:if>

I can only find answers if a JSP is called within a Jquery function, and not this opposite way.

2 Answers 2

1

Why not? Of course, this works.

Your JavaScript code will only be sent to the client by <c:if> if the condition is true.

Sign up to request clarification or add additional context in comments.

1 Comment

As long as you aren't missing <script></script> tags around the JavaScript. Or rather it will be sent to the client but the client still needs to know that it should be evaluated as JavaScript and thus the need for the tags.
1
  <c:set var="myVar"  value="${3000}"/>
<c:if test="${myVar < 1000}">
  <script>
   $(function () {

       alert("Value less than 1000"); 
   });
  </script>
   Variable <c:out value="${myVar}"/>

</c:if>

<c:if test="${myVar > 2000}">
  <script>
   $(function () {

       alert("Greater than 2000"); 
   });
  </script>
   Variable <c:out value="${myVar}"/>

</c:if>

Output :

Variable 3000

4 Comments

I cannot seem to get this to work. I paste this example into my jsp page, and all I get are Unable to compile class for JSP, it is triggered by the <% if (requestAttr) %>. How would this work with c:set?
Can you try this one now.. I began writing in script and mixed java code.. :-(
Same issue: org.apache.jasper.JasperException: Unable to compile class for JSP: With the Logic System that is already in place, I'm really looking for a solution that included a <c:set var="X" value="Y"> and <c:if test="Z">
@Murphy1976 I updated my solution and I tested it, it works. If this still doesn't work for you let me know. See if you have included this in your jsp file <%@taglib uri="java.sun.com/jsp/jstl/core" prefix="c"%>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.