Search code examples
jqueryhtmlvariablesif-statementjquery-click-event

If statements ignoring variables inside click events


I'm new to jQuery,

I'm trying to make something very simple. An if statement inside a click event. When I click a button, if the variable is = 1, something happens, if it is equals something else, something else happens. But it seems the click event is ignoring the if statements. It just runs whatever is inside the if statements.

my code:

HTML:

<button type="button" class="one">Press</button>
<button type="button" class="two">section 2</button>
<button type="button" class="three">section 3</button>
<div class="textbox">
 <h1>hi</h1>
 <p>text</p>
</div>

Jquery:

var y = '.textbox p'
var n = 20

$('.one').click(function() {
  if (n=1) {
    $(y).html("hi hi <br> hi <br><br>");
    $('.textbox h1').html("titulo");
    var a=0
  }
});

$('.two').click(function() {
  if (n=1) {
    $('.textbox p').html("hey <br> hi <br><br>");
    $('.textbox h1').html("sup bro");
    var a=0
  }
  else {
    $('.textbox p').html("variable is not 1");
    $('.textbox h1').html("another");
    var a=0
  }
});

Even if I set the variable = 20, the click event runs whatever is inside the if statement. It's like it ignores the variables or the if statements.

So I dont know whats wrong. What's happening?


Solution

  • One equal sign (=) sets the value of a variable. var foo = "bar"; would set foo to store bar.

    You want to use two equal signs (==), which is a comparison operator. (foo == "bar") would check to see if foo is equal to bar.