March 8, 2013

Jquery Looping through elements created at runtime

Question by dev_darin

i have a list that is passed to a page and the elements are created at runtime. I would like to loop through these elements and preform some action for each element. Under is my code:
for each person that gets created from this list i would like to preform a check on that person. Can someone help me i am only getting the check happening once:

jQuery:

$(document).ready(function() {

    $("#userId").each(function(i){
        if ($("#userId").val != '') {
            alert('not null' + i);
        }
    });                 
});

JSP:

<c:forEach items="${person}" var="person">

<input= type="text" id="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Andbdrew

you cannot have multiple elements on a page with the same id attribute. try using classes instead.

try something like:

$(document).ready(function() {

   $(".userId").each(function(i){
       if ($(this).val() != '') {
           alert('not null' + i);
       }
   });
});

Another thing to note is that .val is a method, so you need to call it to get the value. Use .val() instead of .val. As you have your code now, $(selector).val is a function, so it will never be the empty string you are testing it against.

Also your JSP should be something like:

<c:forEach items="${person}" var="person">

<input= type="text" class="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Starx

Your loop will create multiple element with same ID, first change that. It is better to use class names instead.

<c:forEach items="${person}" var="person">

    <input= type="text" class="user" id="userId-${person.userid}" value="${person.userid}" />
       <!--             ^ Use Class &  ^ Id to uniquely identify the user -->
       First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Next you can use .find() to find even the dynamically generated element. But I recommend using my solutions using the class attribute.

$(".user").each(function(i) {
    if ($(this).val() != '') {
          alert('not null' + i);
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!