迭代嵌套到组和节中的一组输入

时间:2011-08-16 17:33:14

标签: javascript jquery input iteration

我想迭代嵌套到组和部分中的一组输入, 目标是在每个组和部分中执行验证

<script src="jquery/jquery.js"></script>

<div  id="groupA" class="preGroups">

    <div id="section-A1">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>

    <div id="section-A2">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>

    <div id="section-A3">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>

    <div id="section-A4">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>
</div>

<div  id="groupB" class="preGroups">

    <div id="section-B1">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>

    <div id="section-B2">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>

    <div id="section-B3">
    <input name="SRPR1"  type="text">
    <input name="SRPR2"  type="text">
    </div>
    </div>
<script>    

// capture all groups
groups = $('div#[id^=group]'); 
console.log(groups);

// iterate through each group in groups
$.each(groups, function(key, group) {
    console.log(group);

    // iterate through each section in group 
    sections = $('div#[id^=section]'); 
    $.each(sections, function(key, section) {
        console.log(section);

        // iterate inputs in each group
        // more code goes here
        /// console.log(input.name + " " +  input.value);       
    });
});

1 个答案:

答案 0 :(得分:0)

您可能需要sections = $(group).find('div#[id^=section]');而不是sections = $('div#[id^=section]');

修改

完整代码:

groups = $('div[id^="group"]'); 
//console.log(groups);

// iterate through each group in groups
$.each(groups, function(key, group) {
    //console.log(group);

    // iterate through each section in group 
    sections = $(group).find('div[id^="section"]'); 
    $.each(sections, function(key, section) {
        //console.log(section);
        var inputs = $(section).find("input");
        // iterate inputs in each group
        // more code goes here
        inputs.each(function(){
            console.log(this.name + " " +  this.value);
        })
        /// console.log(input.name + " " +  input.value);       
    });
});


Demo