Reputation: 872
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>
Upvotes: 0
Views: 122
Reputation: 58261
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>
Upvotes: 1
Reputation: 401
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; }
Upvotes: 1
Reputation: 122047
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>
Upvotes: 2
Reputation: 96
You use not correct access to elements
<script type="text/javascript">
function valueChanged() {
if ($(this).is(":checked"))
$("#div2").show();
else
$("#div1").hide();
}
</script>
Upvotes: 0