Check the box if it is set and then show div else shows another div

I have a checkbox. If I select the checkbox, I need to display a specific div, and if it is left unchecked, then display another div. Can someone help me with this.

I researched and I only found examples where, if the checkbox is checked, then show the div or hide the div. But my problem is a little different. If this is not possible using the checkbox and possibly with a different field, please let me know. Thanks in advance.

+4
source share
3 answers
document.getElementById('id_of_my_checkbox').onclick = function () { document.getElementById('id_of_div_to_show_when_checked').style.display = (this.checked) ? 'block' : 'none'; document.getElementById('id_of_div_to_hide_when_checked').style.display = (this.checked) ? 'none' : 'block'; }; 
+6
source

If you post HTML, that would be much better.

Otherwise, the general solution:

 var checkbox = document.getElementById("<YOUR-CHECKBOX-ID>"); var firstDiv = document.getElementById("<YOUR-FIRST-DIV-ID>"); var secondDiv = document.getElementById("<YOUR-SECOND-DIV-ID>"); checkbox.onclick = function(){ if(checkbox.checked){ firstDiv.style.display = "block"; secondiv.style.display = "none"; } else { firstDiv.style.display = "none"; secondiv.style.display = "block"; } } 
+3
source

The easiest way to use onClick ..

 <input type="checkbox" onclick="document.getElementById('sp-click').innerHTML = 'Check Box = ' + this.checked;" id="click"> <span id="sp-click"></span> 

You can use this to change the style / visibility of certain divs to hide and show them.

eg.

 <input type="checkbox" onclick="changeClass(this.checked);" id="click"> <script> function changeClass(checkbox){ var divone = document.getElementById('divone') var divtwo = document.getElementById('divtwo') if(checkbox == 'true'){ divone.style.display = "none"; divtwo.style.display = "inline"; } else { divone.style.display = "inline"; divtwo.style.display = "none"; } } </script> 
+1
source

All Articles