0

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>

4 Answers 4

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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>

Comments

0

You use not correct access to elements

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.