jay thakur jay thakur - 5 months ago 16
jQuery Question

How to get size of a list(returning from Controller) in onChange() JQuery

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){

here I am displaying that list:

<tr id = "players" style="display:none;">
<td class="tabHead">PLAYER NAMES</td>
<div class="" id="playerNames" name="playerNames" >
<c:forEach items="${playersList}" var="playersListItem">

I tried -

var count = playersList.length;
var count = $("#players").length;

but that didn't work.


It seems that each item in your list is some unformatted text followed by a <br> element:


...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.)