The username and password login array on the Javascript page is malfunctioning

Struggling to create a login page with javascript? Consider using an array of usernames and passwords for verification. Check out the code below for guidance:

Taris


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

            <script>
             var userArray = [
                 {
                     username: "user1",
                     password: "pw1"
                 },
                 {
                     username: "user2",
                     password: "pw2"
                 },
                 {
                     username: "user3",
                     password: "pw3"
                 }
             ]   

            function loginFunction () {
                    var username = document.getElementById("myText").value;
                    var password = document.getElementById("myText1").value;

                    for(i = 0; i < userArray.length; i++){
                        if(username == userArray[i].username && password == userArray[i].password){
                            alert("Hello");
                        }

                    }    
            }

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

            </script>
         </body>
     </html>
    

Answer №1

function loginFunction () {
        var username = document.getElementById("myText").value;
        var password = document.getElementById("myText1").value;

        for(i = 0; i < userArray.length; i++){
            if(username == userArray[i].username && password == userArray[i].password){
                alert("Hello");
            }

        }    
}

Revamp the HTML code:

<input type="text" id="myText" value="john_doe">
<input type="password" id="myText1" value="PaSsWoRd1234">

Answer №2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <title>Document</title>
    <style>
    </style>
</head>
<body>
    <script src="login.js"></script>
    <input type="username" id="myText" value="">
    <input type="password" id="myText1" value="">
    <button id="button"></button>
    <script>
     var userArray = [
         {
             username: "user1",
             password: "pw1"
         },
         {
             username: "user2",
             password: "pw2"
         },
         {
             username: "user3",
             password: "pw3"
         }
     ]   


function loginFunction () {
        let username = document.getElementById("myText").value;
        let password = document.getElementById("myText1").value;
  let currentUser = userArray.filter( user=& user.username == username && user.password == password)
  currentUser.length ? console.log('Hello'): console.log('Wrong data')
}

const button = document.getElementById("button");
button.addEventListener('click', () =& {
    loginFunction();
});
</script>
</body>
</html>

I trust this snippet will be of assistance to you. If any part is unclear, feel free to reach out with a question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Array of Ogre3D scene nodes

I am currently in the process of developing a procedurally generated city using ogre3d. My goal is to have a city spawn when the player approaches a designated area marked as a city. However, I am facing a challenge in storing the buildings within an arr ...

Preserve menu settings by utilizing local storage

I have been working on saving the state of my menu using localstorage. The jQuery code below is what I am currently using to toggle my menu: <nav id="sidebar" class="active"> <ul class="menu"> <li> <a href="#">Customer ...

Unforeseen behavior in Ajax success callback

My unordered list contains a href link. Initially, only the welcome page is visible on page load. Upon clicking the list for the first time after page load, the desired results are displayed in the corresponding div as expected. The issue arises when swi ...

Google Book API is a tool provided by Google that

I am trying to loop through the items array provided by the Google Books API and display the result within a div, but I'm having trouble doing so. Here is my current code: <body> <div class="main-body"> <form id="form"> ...

Deactivate the collapse toggle feature in the footer navigation

I've recently started using bootstrap and I'm having some trouble adding a social nav footer to my portfolio. I've experimented with removing different classes and even tried using the sticky footer feature, but it's not quite what I ne ...

Creating an empty input field with a predetermined default output in ReactJS

My current challenge involves navigating form data between various components in a React application. I am looking to pass data from child components to parent components and vice versa, creating a seamless flow of information. The key requirement is to ha ...

Tips on utilizing the getElementsByClassName method in JavaScript

Check out this HTML snippet: <html> <body> <div id="wrapper"> <div id="c_wrapper"> <div class="member"> <form name="f1"> </form> </div> ...

React - Struggling to render an image received as a prop within a React component

Just starting out with React. I'm trying to figure out how to properly display an image from the props of my CheckoutProduct component inside an image HTML tag. Image displaying the Product item but failing to do so. Here's the code snippet: i ...

Exploring the power of promise chaining within AWS Lambda

I'm feeling a bit confused about how Promise chaining works in AWS Lambda. exports.handler = async(event) => { firstMethod = () => { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Deactivate a radio button group based on the selection of a previous group

When submitting a pay change request for an employee in the HR Department, there are 2 sets of radio buttons to consider. The 2nd group should only be enabled if "Yes" is selected in the first group. However, if the user switches from "Yes" to something in ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

Adjusting a parameter according to the width of the browser window?

Using Masonry, I have implemented code that adjusts the columnWidth to 320 when the screen or browser window width is less than 1035px. When the width exceeds 1035px, the columnWidth should be 240. However, the current code keeps the columnWidth at 320 re ...

Zooming does not activate the onZoom event

I have created a line chart using react-chartjs-2 and incorporated the chartjs-plugin-zoom plugin. My goal is to have the zoom level displayed in the console whenever the chart is zoomed in or out. However, it seems that the onZoom function is not being tr ...

Enhancing the speed at which Discord fetches usernames for numerous users using discord.js

Below is the code snippet: const memberGroup = ["801555002664419350", "801555002664419351", "801555002664419352", "801555002664419353", "801555002664419354", "801555002664419355", "8015550026 ...

Instruct the user to input a file name before initiating the download of a text file using Angular

Does anyone have experience with downloading content in a txt file? Here is the code snippet I'm working with: download() { let content = "Sample text"; saveAs(new Blob([content], { type: 'text/plain'}), 'sample.txt'); I am usi ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

React state change is causing a functional component to not re-render

When attempting to map out a nested array from the data retrieved by an http request in a functional component, you may encounter a frustrating error: "TypeError: Cannot read property 'map' of undefined". Even though the state is updated correctl ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

instructions to selectively remove additional instructions

In my quest to develop a directive that can impact target elements in various ways, I have encountered three possible scenarios: 1. leaving the element unchanged, 2. removing all other directives before compilation to restrict user interactions (such as ng ...