开发者

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=开发者_JAVA技巧"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.


Loop over divs and then form elements:

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


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


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜