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

Categories

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

javascript - I am stuck in creating a simple verification. How do I take the input entered by user and verify with my data?

I want to take the user input and iterate through my data to check whether it matches or not. How do I verify if the user entered input matches with my data.

const userInput = document.querySelector(".ID");
const button = document.querySelector(".login");
const data = [
  { userName: "Jon", userId: 1, admin: true },
  { userName: "Mike", userId: 2, admin: false },
  { userName: "Martha", userId: 3, admin: false },
];


function checkUser() {
  const id = userInput.value;
  data.forEach((user) => {
    if (id === user.userId) {
      console.log("Welcome");
    } else {
      console.log("Incorrect ID");
    }
  });
}

button.addEventListener("click", (e) => {
  e.preventDefault();
  checkUser();
});
<input class="ID" />
<input type="button" class="login" value="login" />
question from:https://stackoverflow.com/questions/65642465/i-am-stuck-in-creating-a-simple-verification-how-do-i-take-the-input-entered-by

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

1 Answer

0 votes
by (71.8m points)

Input element values are string. For your code to work, you must declare your data.userId as strings.

So it must be:

    const data = [
    { userName: "Jon", userId: "1", admin: true },
    { userName: "Mike", userId: "2", admin: false },
    { userName: "Martha", userId: "3", admin: false },
    ];

If you don't want to use strings as userId, you should change the logical operator of your conditional statement into == instead of === so it would ignore data types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...