问题
I'm working on project where I have fieldset #a like this.
<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>
This fieldset #a checkbox : is checked value is Dynamic.
I have another fieldset #b on the same page.
What I want is to Assign/Copy checkbox : is checked value from fieldset #a to fieldset #b Serially on page load. [ Both fieldset have equal number of checkboxes. ]
<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>
How can I achieve this ? Thanks.
回答1:
You could do it using that selector you mentioned and then looping each of the values, getting their index, and updating the next fieldsets checkboxes according to those indicies.
Like this:
$('fieldset#a input[type="checkbox"]:checked').each(function(){
$('fieldset#b input[type="checkbox"]').eq($(this).index()).prop('checked',true);
});
example: http://jsfiddle.net/niklasvh/hHnLu/
回答2:
You can use something like this:
$( '#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' );
}
} );
回答3:
I was not able to get above stuff working hence I tried below approach and it worked.
// 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);
}
});
Hope this helps!!!
来源:https://stackoverflow.com/questions/6439900/copy-check-state-of-a-set-of-checkboxes-to-another-fieldset