Call javascript from c:foreach

3.8k views Asked by At

I have a requirement to call a javascript function inside c:foreach. Please give me a idea how to call. I will loop through usertimetrackersummary inside foreach and need to call javascript function for every looping.

Now javascript function is called every looping but i'm getting empty value if i try to print 'totalOffHomeHrs' in table data. td

  <c:forEach items="${userTimeTrackerSummary}" var="userTimeTracker">
            <script type="text/javascript">
                var totalOffHomeHrs= addTimes('${userTimeTracker.totalWorkhours}','${userTimeTracker.totalWorkHomehours}');
            </script>
          <tr style="font-size:11px;">
                    <td ><c:out value="${userTimeTracker.employeeID}" /></td>
                    <td>${totalOffHomeHrs}</td>
          </tr>
        </c:forEach>

    javascript function:
    function addTimes(t0, t1) {
          return timeFromMins(timeToMins(t0) + timeToMins(t1));
        }
1

There are 1 answers

0
user2057006 On

Finally i m able to achieve the requirement in below code. Please suggest if there is an alternative elegant way.

<c:forEach items="${userTimeTrackerSummary}" var="userTimeTracker">
           <tr style="font-size:11px;">
                 <td ><c:out value="${userTimeTracker.employeeID}" /></td>
                 <td id="finalWorkHours${userTimeTracker.employeeID}"></td>
                        <script type="text/javascript">
                            var totalOffHomeHrs= addTimes('${userTimeTracker.totalWorkhours}','${userTimeTracker.totalWorkHomehours}');
                            document.getElementById('finalWorkHours${userTimeTracker.employeeID}').innerHTML = totalOffHomeHrs;
                        </script>
              </tr>
            </c:forEach>

javascript function:
function addTimes(t0, t1) {
      times = [];
      times1 = t0.split(':');
      times2 = t1.split(':');

      for (var i = 0; i < 2; i++) {
        times1[i] = (isNaN(parseInt(times1[i]))) ? 0 : parseInt(times1[i])
        times2[i] = (isNaN(parseInt(times2[i]))) ? 0 : parseInt(times2[i])
        times[i] = times1[i] + times2[i];
      }

      var minutes = times[1];
      var hours = times[0];

      if (minutes % 60 === 0) {
        res = minutes / 60;
        hours += res;
        minutes = minutes - (60 * res);
      }

      return hours + ':' + minutes ;
}