2010-06-10 127 views
0

我有六個複選框。多個複選框,檢查是否都在Jquery中檢查

顯示爲這樣

Checkbox1 <input type="checkbox" id="check1"> 

Checkbox2 <input type="checkbox" id="check2"> 

<div id="checkbox1field" {if $blabla} style="display="none"{/if}> 
Checkbox1 <input type="checkbox" id="check3"> 
Checkbox2 <input type="checkbox" id="check4"> 
</div> 

<div id="checkbox2field" {if $blabla2} style="display="none"{/if}> 
Checkbox1 <input type="checkbox" id="check5"> 
Checkbox2 <input type="checkbox" id="check6"> 
</div> 

,如果我現在就點擊複選框以id=check1id=checkbox1field元素應該顯示如果display="none"

如果我點擊id="check3"id="check4"應該隱藏。

如果我點擊id="check4"id="check3"應該隱藏。

相同的過程也適用於id="checkbox2field"

但我的問題是,如果用戶點擊

id="check2" and id="check1" 

我做了什麼。然後我想,無論id="checkbox2field"id="checkbox1field"應該顯示。

我做了哪些工作50%是在這裏

$("#check1:checked").show("fast").("#check4").show("fast").("#checkbox2field").hide("fast"); 
$("#check2:checked").show("fast").("#check1").hide("fast").("#checkbox1field").show("fast"); 

如何解決使用jQuery這個問題呢?

回答

1
$('#check1,#check2').bind('change', function() { 
    var self = $(this); 

    $('#' + self.attr('id') + 'field').toggle(self.attr('checked')).children(':checkbox').show(); 
}); 

$('#check3,#check4,#check5,#check6').bind('change', function() { 
    var self = $(this); 

    self.siblings(':checkbox').toggle(self.attr('checked')); 
}); 

你可能想要把類適用於你的複選框,使選擇更容易。

2

試圖做到這一切所有在一個巨大的jQuery鏈註定要比它的價值更混亂。

這裏有一個簡單,直接的方法:

if ($('#check1').is(':checked')) { 
    if ($('#check2').is(':checked')) { 
     $('#checkbox1field').show('fast'); 
     $('#checkbox2field').show('fast'); 
    } else { 
     $('#checkbox1field').hide('fast'); 
    } 
} else if ($('#check2').is(':checked')) { 
    $('#checkbox2field').hide('fast'); 
}