Tabriz
Tabriz

Reputation: 35

How to use hide function inside if statement

When I click .dot element it should query database and show the result, and in second click it should hide the result. However it just show nothing in first click.

When I leave second if empty it successfully queries the database and show the result. But when I add this code $(".conte").hide(); to second if it shows nothing in click.

here is the code:

$(document).ready(function() {
  var do1 = 0;
  var do2 = 0;
  var do3 = 0;
  var do4 = 0;

  $('.dot1').click(function() {

    if (do1 == 0) {
      do2 = 0; // for other function
      do3 = 0; // for other function
      do4 = 0; // for other function
      do1 = 1;

      $.ajax({
        type: "POST",
        url: "query1.php",
        success: function(data) {
          $(".conte").html(data);
        }
      });
    }
    if (do1 == 1) {
      $(".conte").hide();
      do1 = 0;
      //hide me
    }
    // $(this).toggleClass('clicked');
  });
});

Upvotes: 1

Views: 102

Answers (1)

Barmar
Barmar

Reputation: 781503

Before you send the AJAX request in the first if, you do do1 = 1;. So when you then test if (do1 == 1), this is successful, so you hide .conte.

Change the second if to else if, so you don't run both blocks in the same click. Or use else if these are the only two possible values.

If you're using these for binary states, it's better style to use true and false, not 0 and 1. Then you can write:

do1 = true;

if (do1) {
    do1 = false;
    ...
} else {
    do1 = true;
    ...
}

Upvotes: 1

Related Questions