admin管理员组

文章数量:1287634

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.

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.

Share Improve this question asked Aug 30, 2011 at 17:55 swathi swathi 1074 silver badges13 bronze badges 1
  • 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 Commented Aug 30, 2011 at 17:59
Add a ment  | 

3 Answers 3

Reset to default 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';
};

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";
    }
}

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>

本文标签: phpCheck box if checked then show div else show a different divStack Overflow