1

I am trying to create a working login interface with javascript. I've put down my code but it won't work and it does not show any type of error messages. Thanks Taris

function loginFunction() {
  var x = document.getElementById("myText");
  var y = document.getElementById("myText1");
  console.log(x);
  console.log(y);

  if (x == "Tom" && y == "Halo") {
    window.open("www.youtube.de");
  }
}

const button = document.getElementById("button");
button.addEventListener('click', () => {
  loginFunction();
});
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
Taris
  • 27
  • 6
  • 1
    Please keep in mind that client-side input validation is not secure. But I assume that you are aware of it. – smolo May 11 '20 at 08:20

3 Answers3

3

You need to access the .value of the elements x and y - you're dealing with the element, not the value:

if (x.value == "Tom" && y.value == "Halo") { ... }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You forgot to add .value to selected text field.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="username" id="myText" value="Tom">
    <input type="password" id="myText1" value="Halo">
    <button id="button">login</button>
    <script>


function loginFunction () {
    var x = document.getElementById("myText").value;
    var y = document.getElementById("myText1").value;
        console.log(x);
        console.log(y);

    if(x === "Tom" && y === "Halo") {
        console.log("login in");
        //window.open("www.youtube.de");
    }
    else
    {
      console.log("failed");
    }
}

const button = document.getElementById("button");
button.addEventListener('click', () => {
    loginFunction();
});

    </script>
</body>
</html>
Ferin Patel
  • 3,424
  • 2
  • 17
  • 49
1

The problem is that you are reading the value of those input elements. You have assigned the input itself to the variable.

 var x = document.getElementById("myText").value;

function loginFunction() {
  var x = document.getElementById("myText").value;
  var y = document.getElementById("myText1").value;
  console.log(x);
  console.log(y);

  if (x === "Tom" && y === "Halo") {
    alert('open page')
    //window.open("https://youtube.de");
  }
}

const button = document.getElementById("button");
button.addEventListener('click', () => {
  loginFunction();
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="username" id="myText" value="Tom">
  <input type="password" id="myText1" value="Halo">
  <button id="button">login</button>
</body>

</html>
The Fool
  • 16,715
  • 5
  • 52
  • 86