简体   繁体   中英

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" />

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM