st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

jQuery Loop Question

I have a quick question re. the most efficient way to loop through multiple divs and the input /textarea's in those divs.

For example, I have the following HTML

    <div class="formatInput">
        <h4>Section Header</h4>
        <input type="text" class="formatSectionHeader" width="100%"/>
        <h4>Section Content</h4>
        <textarea class="formatSectionContent"></textarea>
        <p style="float:right;"><span class="removeFormatInput">Remove Section</span></p>
    </div>

I made a button that will allow the user to add more .formatInput divs if needed.

At the end of it I have a refresh button that I want to loop through each div and gather the values of the input and textarea controls in order.

Upvotes: 1

Views: 206

Answers (5)

Nick Hagianis
Nick Hagianis

Reputation: 1468

The following would create two separate arrays. Really depends on what you'll be doing with the data as to how you'd want to format it. jAndy hit it right on the head but I can't vote yet.

var header = new Array();
var content = new Array();

$(".formatInput").each(function(){
    iDex = $(this).index();
    header[iDex] = $(this).children(".formatSectionHeader").val();
    content[iDex] = $(this).children(".formatSectionContent").val();
});

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382636

You can use each to loop through all the fields inside your div like this:

$('.formatInput :input').each(function() {
    alert($(this).value());
});

The :input filter selects will select all inputs (in your case input type text and textarea) which are inside the div with class formatInput and then each is used to loop over them.

Upvotes: 0

Andy Gaskell
Andy Gaskell

Reputation: 31761

One thing worth at least mentioning is that you might be looking for serialize, although I can't say for sure. The reason I say this is because of this wording.

loop through each div and gather the values of the input and textarea controls in order

Like I said though, maybe you really are just looking for a couple of each calls.

Upvotes: 1

zwippie
zwippie

Reputation: 15515

Loop over divs and then form elements:

$('.formatInput').each(function(index) {
  $(':input', this).each(function(index2)) {
    alert(index + '-' + index2 ': ' + $(this).value());
  });
});

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

if you call $(".formatInput") it will give you all the divs with the class formatInput. Traverse it using .each().

$(".formatInput").each(function(){
   // $(this) here will be the current div in the loop.
});

Upvotes: 1

Related Questions