Reputation: 151
I am returning a list from Controller class.
httpReq.setAttribute("playersList", playersList);
I want size of this list in onchange() method.
$('#teams').on('change', function(){
// code to get the size/count
if(count < 11){
.........
}else{
.........
}
}
here I am displaying that list:
<tr id = "players" style="display:none;">
<td class="tabHead">PLAYER NAMES</td>
<td>
<div class="" id="playerNames" name="playerNames" >
<c:forEach items="${playersList}" var="playersListItem">
${playersListItem.name}<br>
</c:forEach>
</div>
</td>
</tr>
I tried -
var count = playersList.length;
var count = $("#players").length;
but that didn't work.
Upvotes: 1
Views: 2392
Reputation: 150080
It seems that each item in your list is some unformatted text followed by a <br>
element:
${playersListItem.name}<br>
...all within a particular <div>
within a particular <tr>
. So to count them just count the <br>
elements that are inside the <tr>
or <div>
using one of the following:
var count = $("#players").find("br").length;
var count = $("#players br").length;
var count = $("#playerNames").find("br").length;
var count = $("#playerNames br").length;
(Note that the second thing you tried, $("#players").length
, should always return either 0 or 1, because selecting by element id should always find either 0 or 1 element.)
Upvotes: 1
Reputation: 32354
How about using a tribute selector
$("[id='players'] br").length;
or
$('#playerNames > *').length;
Upvotes: 1
Reputation: 26332
if you change your table structure a little, you can easily find the count. Like here I add class 'playerName' and count it inside the players TR tag
<tr id="players" style="display:none;">
<td class="tabHead">PLAYER NAMES</td>
<td>
<div id="playerNames" name="playerNames" >
<c:forEach items="${playersList}" var="playersListItem">
<div class="playerName">${playersListItem.name}</div>
</c:forEach>
</div>
</td>
</tr>
$('#players .playerName').length
Upvotes: 0