0

$(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

1
  • 1
    Don't you need to set passInput within the click function? Otherwise won't it run on page load and the value will be empty all the time? Commented Jan 12, 2015 at 1:38

3 Answers 3

2

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");
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

-1

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

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.