Ronald
Ronald

Reputation: 299

Get current value jstl foreach in jquery

I want to know how to get the current value in an element of the loop forEach in JSTL, my code is :

<c:forEach var="mc1" items="${lstMedCon1}">
  <div class="row" style="text-align: center;color:#186793;"> 
    <span id="idEspeciality" class="label label-default" style="background:#186793;font-size: 30px;">${mc1.strEspeciality}</span>
  </div>
</c:forEach>

in javascript

function goNext() {
   console.log($("#idEspeciality").text());
}

In my code the function goNext() is called for setInterval(goNext, 6000) and for each intervalue the text change in the view, so I want to get the current value in js but the same value is printed in console which is the first value of the list, but in the view the value is changed

Upvotes: 0

Views: 1825

Answers (1)

Roman C
Roman C

Reputation: 1

You should have unique id of the tag which value you get. Add a status variable to forEach tag to index IDs.

<c:forEach var="mc1" items="${lstMedCon1}" varStatus="stat">
  <div class="row" style="text-align: center;color:#186793;"> 
    <span id="idEspeciality${stat.index}" class="label label-default" style="background:#186793;font-size: 30px;">${mc1.strEspeciality}</span>
  </div>
</c:forEach>

Now you can get the value

function goNext(index) {
   console.log($("#idEspeciality"+index).text());
}

The index parameter you can get from ID attribute while inspecting DOM elements generated via forEach tag or entering manually.

Upvotes: 1

Related Questions