将一组复选框的检查状态复制到另一个字段集

时间:2011-06-22 12:33:32

标签: jquery checkbox

我正在开展项目,我的 fieldset #a 就像这样。

<fieldset id="a">
      <input type="checkbox" name="c1" value="v1" checked="checked" />
      <input type="checkbox" name="c2" value="v2"/>
      <input type="checkbox" name="c3" value="v3"/>
</fieldset>

字段集#a 复选框:已选中值为动态。

我在同一页面上有另一个字段集#b

我想要的是分配/复制复选框:在页面加载时从字段集#a到字段集#b 系列检查值。 [两个字段集都有相同数量的复选框。 ]

<fieldset id="b">
      <input type="checkbox" name="cc1" value="vv1"/>
      <input type="checkbox" name="cc2" value="vv2"/>
      <input type="checkbox" name="cc3" value="vv3"/>
</fieldset>

我怎样才能做到这一点?感谢。

3 个答案:

答案 0 :(得分:3)

您可以使用您提到的选择器,然后循环每个值,获取索引,并根据这些指示更新下一个字段集复选框。

像这样:

$('fieldset#a input[type="checkbox"]:checked').each(function(){   
    $('fieldset#b input[type="checkbox"]').eq($(this).index()).prop('checked',true);
});

示例:http://jsfiddle.net/niklasvh/hHnLu/

答案 1 :(得分:0)

您可以使用以下内容:

$( '#b' ).children( 'input:checkbox' ).each( function( i ) {
    var aChecked = $( '#a' ).children( 'input:checkbox' ).eq( i ).prop( 'checked' );
    if ( aChecked )
    {
        $( this ).prop( 'checked', true );
    }
    else
    {
        $( this ).removeProp( 'checked' );
    }
} );

答案 2 :(得分:0)

我无法完成上述工作,因此我尝试了以下方法并且有效。

// lets uncheck all the checkboxes in first fieldset                                                                                             
$('#b input[type=checkbox]').removeProp('checked');                                    

  cj('#b [type=checkbox]').each(function() {
     if (cj(this).prop('checked') ) {
         // here get the index of current element 
         // then modify below code to set prop checked
         cj('#a [type=checkbox]').prop('checked',true);
     }
});

希望这有帮助!!!