Ayman Ayman - 7 months ago 14
Javascript Question

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>

Answer

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>

Comments