Murad Elboudy
Murad Elboudy

Reputation: 117

jquery click function not working with an if statement

$(function() {
  var passInput = document.getElementById("pass").value;
  $('#btn').click(function() {
    if (passInput === 1234) {
      alert("Correct");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="passwordEntryDiv">
  <input id="pass" type="password">
  <button id="btn">Submit</button>
</div>

Why isn't this working? this isn't for a website or anything just something I'm doing

Upvotes: 0

Views: 55

Answers (3)

charlietfl
charlietfl

Reputation: 171679

Very simple, you are storing the value of the input on page load. That variable will not update as user enters data. So it never changes from being an empty string.

Now access the value inside the button click instead and you have updated value to validate

  $('#btn').click(function() {
    /* get value when click occurs*/
    var passInput = 1*$("#pass").val();
    if (passInput === 1234) {
      alert("Correct");
    }
  });

Also values are strings so if testing against a number you need to convert string to number. Lots of ways to convert to number.

Upvotes: 1

Khaltazar
Khaltazar

Reputation: 296

It's an input field so the value would be "1234" not 1234.

Change: passInput === 1234

To: passInput === "1234"

Also, place the value inside of the click event.

$("#btn").click(function () {
    if ($("#pass").val() === "1234") {
        alert("Correct");
});

Upvotes: -1

Mike
Mike

Reputation: 4091

The value of passInput is only being set set once, when the code is ran -- it will never update in the code you've provided. When the user clicks the button, it is comparing that original value to 1234, not the current value in the text box. Put it inside your click handler to get a new value every time the click happens.

$(function () {
  $('#btn').click(function() {
    var passInput = document.getElementById("pass").value;
    if (passInput === 1234) {
      alert("Correct");
    }
  });
});

Upvotes: 2

Related Questions