Home > OS >  JavaScript Password function outputs wrong data
JavaScript Password function outputs wrong data

Time:12-17

Updated version:
The new version looks like this, but still doesnt work, any fixes

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw").value;
  
  if (x.value === "") {
    alert("no password entered");
  } else if (x.value !== pw) {
    alert("wrong password");
  } else {
    alert("correct pw");
  }
}
<html>

<head>
  <title>Hello</title>
</head>

<body>
  <input type="password" id="pw" oninput="">
  <button type="submit" onclick="checkpw(event, this)">submit</button>
</body>

</html>

The code above still only outputs wrong password.

CodePudding user response:

You need to access the value of the input field to get the appropriate text value to compare. Also, your logic should check for empty first then wrong.

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw"); // could be `input` instead
  
  if (x.value === "") {
    console.log("no password entered");
  } else if (x.value !== pw) {
    console.log("wrong password");
  } else {
    console.log("correct pw");
  }
}
<input type="password" id="pw" oninput="checkpw(event, this)">

I recommend wrapping the field in a form form.

Note: Never perform authentication on the client.

const loginForm = document.forms.login;
const expectedPassword = '1234';

const authenticate = (event, form) => {
  event.preventDefault();

  const actualPassword = new FormData(form).get('password').trim();

  console.log(checkPassword(actualPassword));
};

const checkPassword = (actualPassword) => {
  if (actualPassword.length === 0) {
    return 'No password entered';
  } else if (actualPassword !== expectedPassword) {
    return 'Wrong password';
  } else {
    return 'Correct pw';
  }
};
<form name="login" onsubmit="authenticate(event, this)" autocomplete="off">
  <label for="pw">Password</label>
  <input type="password" id="pw" name="password" />
  <button type="submit">Submit</button>
</form>

CodePudding user response:

function checkpw() {
  var x = document.getElementById("pw");
  var pw = "1234";
  if (x.value == pw) {
  //--------^ the variable x refers to the element itself. x.value is what you are looking for
      alert("correct pw");
  } else if(x.value == "") {
  //--------^ pw equals to "1234" which is the variable you created. replace pw with x.value instead (consider doing x.value.trim())
      alert("no password entered");
  } else {
      alert("wrong password");
  }
}
<input type="password" id="pw" />
<!---------------------^ I've added an id attribute since your code uses getElementById and that requires an id --->
<button onclick="checkpw()">Check password</button>

  • Related