Show/hide Div If Checkbox Selected
I need a page with checkboxes and visible div if at minimum 1 is checked. Here I got page that if i check checkbox, the div will show. It's okay and works correctly. When I check
Solution 1:
change the input boxes like
<inputtype="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<inputtype="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<inputtype="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<inputtype="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
and js code as
functionshowMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for(var i=0;i<chboxs.length;i++) {
if(chboxs[i].checked){
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
here is a demo fiddle
Solution 2:
You would need to always consider the state of all checkboxes!
You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.
So you always need to check all of them:
<scripttype="text/javascript">
<!--
functionshowMe (it, box) {
// consider all checkboxes with same namevar checked = amountChecked(box.name);
var vis = (checked >= 3) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
functionamountChecked(name) {
var all = document.getElementsByName(name);
// count checkedvar result = 0;
all.forEach(function(el) {
if (el.checked) result++;
});
return result;
}
//--></script>
Solution 3:
<inputtype="checkbox"name="check1"value="checkbox"onchange="showMe('div1')" /> checkbox
<divid="div1"style="display:none;">NOTICE</div><scripttype="text/javascript">
<!--
functionshowMe (box) {
var chboxs = document.getElementById("div1").style.display;
var vis = "none";
if(chboxs=="none"){
vis = "block"; }
if(chboxs=="block"){
vis = "none"; }
document.getElementById(box).style.display = vis;
}
//--></script>
Post a Comment for "Show/hide Div If Checkbox Selected"