Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - if statement doesnt work when included with two variables

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...