当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - show div and hide another div using checkbox

问题描述:

i need to hide div1 and show div2 when checkbox1 is checked

i have used below code but it didn't work

<script type="text/javascript">

function valueChanged() {

if ($('.checkbox1').is(":checked"))

$(".div2").show();

else

$(".div1").hide();

}

</script>

Html

<input type="checkbox" name="checkbox1" onchange="valueChanged()" />

<div class="row" id="div1">Show Div 1</div>

<div class="row" id="div2" style="display: none">Show Div 2</div>

网友答案:

Instead you can just use toggle()

function valueChanged() {
  $('.row').toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" onchange="valueChanged()" />
<div class="row show" id="div1">Show Div 1</div>
<div class="row" id="div2" style="display: none">Show Div 2</div>
网友答案:

If you want to keep it JS based your logic isn't quite right. Corrections below:

HTML Update:

<input id="checkbox1" type="checkbox" name="checkbox1" onchange="valueChanged()">
<div class="row" id="div1">Show Div 1</div>
<div class="row" id="div2" style="display: none;">Show Div 2</div></div>

Javascript:

<script type="text/javascript">
    function valueChanged() {
        if ($("#checkbox1").is(":checked")) {
            $("#div2").show();
            $("#div1").hide();
        } else {
            $("#div1").show();
            $("#div2").hide();
        }
    }
</script>

If you want to do it with just CSS instead add a class or id to the checkbox as well and use the ~ selector. You'll also want to remove the inline display none on the div2.

#div2 { display:none; }
#checkbox:checked ~ #div1 { display:none; }
#checkbox:checked ~ #div2 { display:block; }
网友答案:

You code is not correct. It should be like this:

function valueChanged() {
  if ($('#checkbox1').is(":checked")) {
    $("#div1").hide();
    $("#div2").show();
  } else {
    $("#div1").show();
    $("#div2").hide();
  }
}

// OR you could just use toggle()
function valueChanged2() {
  $('.row').toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1" onchange="valueChanged()"  />
<div class="row" id="div1">Show Div 1</div>
<div class="row" id="div2" style="display: none">Show Div 2</div>
网友答案:

You use not correct access to elements

<script type="text/javascript">
    function valueChanged() {
        if ($(this).is(":checked"))
            $("#div2").show();
        else
            $("#div1").hide();
    }
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: