简体   繁体   中英

Show a div on click and hide the other div and oposite

I am trying to: When I click a button to have a div1 show and the div2 hide, and when I click it again to do the opposite, div 2 hide and div1 show. I managed to achieve only the first part.

Jquery:

<script type="text/javascript">
  $(document).ready(function() {
    $("#insert").on('click', function() {
      $(".subtable").hide();
      $(".insert-field").show();
    });
  });
</script> 

HTML

<input type="button" name="insert" id="insert" value="Insert Subscriber(s)">
    <table class="subtable">...</table>
    <div class="insert-field">...</div>

What am I missing?

You can use toggle() to change the display of an element. If it is hidden it will be shown. And if shown, will be hidden. That's the easiest way to just flip things back and forth.

The other way would be to either check whether the element is hidden, or keep track of the state in a separate variable to which you can refer to know whether to hide or show.

Use jQuery.toggle() . Depending on your implementation, you can set the argument of .toggle() as true or false, based on the .visible property of another element.

$("button").click(function(){
   $("p").toggle();
}); 

Here is a quick tutorial to help you.

W3SCHOOLS

$(document).ready(function(){
  var flag = true;
  $("#button").on('click',function(){
      if(flag == true){
        $("#div1").show();
        $("#div2").hide();
        flag =false;
       }else{
          $("#div1").hide();
          $("#div2").show();
          flag =true;
         }
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM