[英]Show a div when at least one checkbox is checked, but hide after last checkbox is unchecked
當頁面上的至少一個復選框被選中時,我使用這些腳本顯示div。
在頁面加載時,未選中所有復選框。 如果用戶選中一個,則顯示一個隱藏的div。 我為此使用了兩個腳本。
在這里找到的第一個http://api.jquery.com/checked-selector/
<script>
var countChecked = function() {
var n = $( "input:checked" ).length;
$( "#count" ).text( n + (n === 1 ? " is" : " zijn") + " aangevinkt!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
</script>
第二個腳本顯示一個隱藏的div #maak_deel
<script>
$( "input[type=checkbox]" ).on( "click", function() {
$("#maak_deel").fadeIn();
});
</script>
由於我是新手,所以我有兩個問題。
1)如何將這兩個腳本合並到一個腳本中(使我的代碼更簡潔)
2)如果用戶選中一個(= div顯示),但是我下定決心並再次取消選中該復選框,如何隱藏div #maak_deel。 現在什么也沒有發生,我希望div再次消失。 我嘗試過切換,但效果不佳。
非常感謝您的幫助!
您可以在計數功能中包含隱藏和顯示代碼。
<script>
var countChecked = function() {
var n = $( "input:checked" ).length; //n now contains the number of checked elements.
$( "#count" ).text( n + (n === 1 ? " is" : " zijn") + " aangevinkt!" ); //show some text
if(n == 0){
$("#maak_deel:visible").fadeOut(); //if there are none checked, hide only visible elements
} else {
$("#maak_deel:hidden").fadeIn(); //otherwise (some are selected) fadeIn - if the div is hidden.
}
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
</script>
當然,這必須在DOM加載后執行,因此可以在代碼的末尾或將代碼包裝在jQuery的$(document).ready(function(){//代碼在此處;})中;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.