Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Looping through elements created at runtime

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>
like image 640
devdar Avatar asked Mar 08 '13 16:03

devdar


1 Answers

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>
like image 51
Andbdrew Avatar answered Oct 19 '22 02:10

Andbdrew