Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to create a simple login system with the help of javascript. Unfortunately, the if statement doesn't work as I've intended it to. The page doesn't redirect when the enter key is pressed.

var objPeople = [
	{studentid: "input1"},
	{studentid: "input2"}
]

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event){
    for(i = 0; i < objPeople.length; i++){
      if (myInput == objPeople[i].myInput && event.keyCode === 13){
        window.location.href = "www.google.com"; 
      }
    }
  });
<html>
    <head>
        <script LANGUAGE="JavaScript" src="JavaScript.js"></script>
        <title>aaa</title>
    </head>
    <body>
        <input type="text" id="myInput">
    </body>
</html>
   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

myInput is undefined for your event, you should get the value by adding following line in your eventListener.

 let myInput= document.getElementById("myInput").value;

Change your code like following.

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
  let myInput = document.getElementById("myInput").value;
  for (i = 0; i < objPeople.length; i++) {
    if (myInput == objPeople[i].studentid && event.keyCode === 13) {
      console.log(objPeople[i].studentid);
      window.location.href = "https://www.google.com";
    }
  }
});

Edit: Sample

var objPeople = [{
    studentid: "input1"
  },
  {
    studentid: "input2"
  }
]

var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
  let myInput = document.getElementById("myInput").value;
  for (i = 0; i < objPeople.length; i++) {
    if (myInput == objPeople[i].studentid && event.keyCode === 13) {
      console.log(objPeople[i].studentid);
      window.location.href = "https://www.google.com";
    }
  }
});
<html>

<head>
  <script LANGUAGE="JavaScript" src="JavaScript.js"></script>
  <title>aaa</title>
</head>

<body>
  <input type="text" id="myInput">
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...