javascriptbuttonclick

Button not working on first click with if and else statements


I am trying to make the navigation work on first click of the button. But for some reason the button won't work on first click and works fine on second click

function authenticate() {
  let x = document.getElementById('aut').value;
  if (x == 'code') {
    document.getElementById('myButton').onclick = function() {
      window.location.href = 'https://www.google.com';
    };
  } else {
    alert('Please check your password')
  }
  console.log('If this message appears in the console, JavaScript is running.');
}
<div>
  <label for="auth">Password:</label>
  <input type="password" name="auth" id="aut">
  <button id="myButton" onclick="authenticate()">Authenticate</button>
</div>


Solution

  • On first click, you only changed the button's onclick handler, not execute it. On second click, you executed the changed handler. It seems like you don't need to change the handler, just execute it right away.

    function authenticate() {
      let x = document.getElementById('aut').value;
      if (x == 'code') {
        window.location.href = 'https://www.google.com';
      } else {
        alert('Please check your password')
      }
      console.log('If this message appears in the console, JavaScript is running.');
    }