![](/img/trans.png)
[英]How to show div, if one of the checkboxes is checked (with a different name on each checkbox)?
[英]Show a div if 2 specific checkboxes are checked, show another if 1 checkbox is checked (don't show it if the 2 checkboxes are checked)
我的代碼中有3個不同的divs紅色,綠色和藍色框,我想顯示這些divs,具體取決於選中了哪些復選框。
目的是:如果選中了藍色復選框,則應顯示藍色div。 如果選中綠色div,則應顯示綠色div。 但是,要顯示紅色div,應選中紅色和綠色復選框。
這些在我的代碼中有效,但是有問題。 如果選中了紅色和綠色復選框,則會顯示紅色div,但也會顯示綠色div。
我需要您的幫助是:如果選中了紅色和綠色復選框,則應顯示紅色div,但不應顯示綠色復選框。 (如果僅選中綠色復選框,則應顯示綠色div。)
謝謝您的幫助!
這是代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Using Checkboxes</title>
<style type="text/css">
.box{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red{ background: #ff0000; }
.green{ background: #00ff00; }
.blue{ background: #0000ff; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($('#red').is(':checked') && $('#green').is(':checked'))
{
$(".red").show();}
else{ $(".red").hide();
}
if($('#green').is(':checked'))
{
$(".green").show();}
else{ $(".green").hide();
}
if($('#blue').is(':checked'))
{
$(".blue").show();}
else{ $(".blue").hide();
}
});
});
</script>
</head>
<body>
<div>
<label><input type="checkbox" id="red" name="colorCheckbox" value="red"> red</label>
<label><input type="checkbox" id="green" name="colorCheckbox" value="green"> green</label>
<label><input type="checkbox" id="blue" name="colorCheckbox" value="blue"> blue</label>
</div>
<div class="red box">You have selected <strong>red and green checkbox</strong> so i am here</div>
<div class="green box">You have selected <strong>green checkbox</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue checkbox</strong> so i am here</div>
</body>
</html>
$('input[type="checkbox"]').click(function () {
$('.box').hide();
if ($('#blue').is(':checked')) $('.blue.box').show();
if ($('#green').is(':checked') && !$('#red').is(':checked')) $('.green.box').show();
if ($('#red').is(':checked') && $('#green').is(':checked')) $('.red.box').show();
});
您問題中的邏輯是正確的!
只需將這些要求轉換為代碼,您便會准備就緒!
//If the blue checkbox is checked, it should show the blue div.
if($('#blue').is(':checked')) {
$(".blue").show();
} else {
$(".blue").hide();
}
//If the green div is checked, it should show the green div.
if($('#green').is(':checked')) {
$(".green").show();
} else {
$(".green").hide();
}
//To show the red div, the red AND the green checkbox should be checked
//but not the green box.
if($('#red').is(':checked') && $('#green').is(':checked')) {
$(".red").show();
$(".green").hide();
} else {
$(".red").hide();
//no show green necessary, it will be handled above
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.