4

I have a check box. If i select the check box then i need to display a particular div and if it is left unchecked then display another div . Can someone help me regarding this.

I have researched and i have only found examples where if the checkbox is checked then show the div or else hide the div.But my issue is a little bit different. If this is not possible with a check box and is possible with some other field also please let me know. Thanks in advance.

swathi
  • 107
  • 4
  • 13
  • can you show what you have tried ? you only need to change hide code to add support of show second div. and on show code to add support of hide second div – Vivek Goel Aug 30 '11 at 17:59

3 Answers3

6
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';
};
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
3

If you post the HTML it would have been much better.

Otherwise a generic 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";
    }
}
Chandu
  • 81,493
  • 19
  • 133
  • 134
1

More simply use onClick..

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

<span id="sp-click"></span>

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

e.g.

<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>
Wez
  • 10,555
  • 5
  • 49
  • 63