开发者

Check box if checked then show div else show a different div

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 r开发者_开发知识库esearched 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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜