user735566
user735566

Reputation: 471

can we use a .each within a .each in jquery?

$("[name=form_1]").each(function(){
    alert("i in else"+i);
    $('.eform_text').each(function() {
    });
});

would this loop iterate over all elements that have a class of eform_text only in form1 .Or would it iterate over all elements which have that class ?

Update:

The exact jsp code is as follows:

<c:when test="${eformDetails.controlType==1}"> <input id="textBox_${eformDetails.id}_${eformDetails.required}_${i}" class="eformDetail eform_text" type="text" value="" name="form_${i}" onblur="validateEformInputs(${i-1})"></input> </c:when>

i have the form which varies each time.and for each form i need to obtain all the text boxes.Currently after your help my javascript is ass follows:

$("[name=form_"+i+"]").each(function(i){ alert("i in else"+i);

         $('.eform_text', this).each(function() {
        textboxId = $(this).attr("id");

It reaches the first alert but i am not able to reach the second loop.It is not obtaining elements that have class eform_text.Not sure what is going wrong here.Could you please help?

Upvotes: 6

Views: 16467

Answers (3)

jeanm
jeanm

Reputation: 1273

$('.element').each(function(){

    $(this).find('.elementChild').each(function(){

        // do something

    });

});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

It would iterate over all elements with that class, whether inside a form with the name "form_1" or not. To only look within each form (I'm guessing you must have more than one form with the name "form_1", though that seems odd), use find in the outer loop in order to scope the inner loop:

$("[name=form_1]").each(function(formIndex) {
    alert("formIndex in each: " + formIndex);
    $(this).find('.eform_text').each(function(textIndex) {
        alert("textIndex in each: " + textIndex);
    });
});

Or you can use the second argument to $(), which provides the context in which to work:

$("[name=form_1]").each(function(formIndex) {
    alert("formIndex in each: " + formIndex);
    $('.eform_text', this).each(function(textIndex) {
        alert("textIndex in each: " + textIndex);
    });
});

Either should work.

Note that as @Shrikant Sharat pointed out in the comments (thanks Shrikant!), I've assumed the i in your original code is meant to be the index that gets passed into each. I've shown the indexes at both levels (with descriptive names) above.

Upvotes: 13

rockerest
rockerest

Reputation: 10508

Your second answer.

Because you're calling $( each time, it instantiates a new copy of the jQuery object which doesn't care what level of a function it's in.

It would loop through every element with that class.

Upvotes: 1

Related Questions