Jquery looping through elements created at runtime

I have a list that gets passed to the page, and elements are created at runtime. I would like to skip these elements and make some steps for each element. Under my code: for every person who is created from this list, I would like to sign up for a check of this person. Can someone help me, I only get a check that happens 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>
+5
source share
4 answers

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

try something like:

$(document).ready(function() {

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

: .val - , , . .val() .val. , $().val , , .

JSP :

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

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

, . .

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

.find(), . , class.

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

@Andbdrew, id, , , .

, this $("#userId") .

, - :

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

Why don't you choose using TAG jQuery. For example, an element that has a list of your users is a table with tblUsers identifiers, then you can use these TRs or TDs for the runtime, as shown below:

$("#tblUsers tr").each(function(i){
        alert('td' + i);
 });   

further, if you have input in tds, you can enter a large selection as

$("tblUsers tr td input")
+1
source

All Articles