Wednesday, May 14, 2014

How to call jquery function from JSP page conditionally

Sometimes we might need to write a jquery function in jsp page and we might need to call it only when it is required or based on certain conditions.

Say we have a boolean attribute based on which we have to call jquery function.

Setting an attribute on server side


We set an attribute on server side using
 req.setAttribute("myAttribute", true);  // On Server Side

on jsp page use <% % > tags to write java code and get that attribute.

Getting attribute in JSP


<%  boolean myAttribute = (Boolean)req.getAttribute("MyAttribute") %>


Now, if that boolean is true write your jquery script.

Calling Jquery function in JSP


<%  if( myAttribute) {%>
<script>
   $(function () {
      alert("Called Jquery from JSP conditionally")
})
</script>
<%}%>


Or you can use taglib library

Example for calling jquery in JSP:


 <c:set var="myAttribute"  value="${5}"/>
<c:if test="${myAttribute< 10}">
  <script>
   $(function () {

       alert("Called Jquery from JSP conditionally");
   });
  </script>
   Variable <c:out value="${myAttribute}"/>

</c:if>




No comments:

Post a Comment