Search code examples
javajavascriptjquerytaglibjspx

How to call javascript function from tag lib's?


Well, I have a question regarding javascript, how to call a js function from jsp or jspx files.

on my jspx page I have a loop which adds data to a table, here is the code sample

<c:forEach items="${loadList}" var="load">
   <tr>
     <td>
       <nobr><c:out value="${load}"/></nobr>
     </td>
  </tr>
</c:forEach>

Here the line no 3 does a c:out on the load var which prints as

55.959090909090904
118.94545454545454
133.46818181818182
19.727272727272727

etc values. So I have written a js function to round of this values to as

55.95
118.94
133.46
19.72

JS function

function roundOfValue(value, limit) {
    value = value.toFixed(limit);
    return value;
}

I am trying to call this function in the c:out as

<nobr><c:out value="roundOfValue(${system},2);"/></nobr>

but this does not call the function and prints the same on the UI. Is there a way to call this function which will prints the rounded off values.

I even tried the following but it does not work

1. <c:forEach items="${systemList}" var="system" varStatus="row">
2.  <tr><td id="load">
3.   <nobr><div id="div"></div>
4.    <script>
5.     document.getElementById(div).innerHTML =  roundOfValue(${system},2);
 6.   </script></nobr>
4.  </td></tr>
5. </c:forEach>

Please suggest some steps to do this. Thanks


Solution

  • Use JSTL instead of JS:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    
    <nobr><fmt:formatNumber value="${load}" pattern="0.00"/></nobr>