Reputation: 5654
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>
Upvotes: 5
Views: 3987
Reputation: 6021
Why don't you select with TAG by jQuery. For example the element having your users list is a table with id tblUsers then you can itereate over runtime generated TRs or TDs as following:
$("#tblUsers tr").each(function(i){
alert('td' + i);
});
further if you have inputs in tds you can go deep in selection as
$("tblUsers tr td input")
Upvotes: 1
Reputation: 12805
As @Andbdrew said, use a class instead of an id, as it will stop looking for more items after it finds the first that matches the id.
Also, you'll want to use this
instead of $("#userId")
inside our function.
So do something like this:
$(".userClass").each(function(i) {
if ($(this).val() != '') {
alert('not null' + i);
}
});
Upvotes: 2
Reputation: 78981
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);
}
});
Upvotes: 3
Reputation: 11895
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>
Upvotes: 5