1

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.

5 Answers 5

1

Loop over divs and then form elements:

$('.formatInput').each(function(index) {
  $(':input', this).each(function(index2)) {
    alert(index + '-' + index2 ': ' + $(this).value());
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.
});

Comments

1

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.

Comments

0

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.

Comments

0

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.