Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Project</title>
</head>
<body>

   <label id =myLabel>Enter your friends name:</label><br>
   <input id="textField" type="text" placeholder="Enter name"><br>
   <button id="submitBtn" type="button">Submit</button><br>
   <p id="outputName"></p>

    
    

    <script src="index.js"></script>
</body>
</html>
let username = document.getElementById("textField").value;
let submit = document.getElementById("submitBtn");
let output = document.getElementById("outputName");


submit.onclick = function(){
    if(username === "Rodney" || username === "rodney"){
        output.innerHTML = username + " access denied";
        
    }
        
    else if(username === "Alexander" || username === "alexander"){
        output.innerHTML = username + " access granted";
        
    }
    else{
        output.innerHTML = username + " not defined";
    }

}

I am looking to display the name along with whether access is granted or denied in the paragraph tag with the ID of outputName.

Answer №1

You've successfully captured an empty username input when the user hasn't typed anything yet

Remember to retrieve the value on onclick

let submitButton = document.getElementById("submitBtn");
let displayOutput = document.getElementById("outputName");


submitButton.onclick = function(){
    let enteredUsername = document.getElementById("textField").value;
    if(enteredUsername === "Rodney" || enteredUsername === "rodney"){
        displayOutput.innerHTML = enteredUsername + " access denied";
        
    }
        
    else if(enteredUsername === "Alexander" || enteredUsername === "alexander"){
        displayOutput.innerHTML = enteredUsername + " access granted";
        
    }
    else{
        displayOutput.innerHTML = enteredUsername + " not defined";
    }

}

or

let usernameInputField = document.getElementById("textField")
let submitButton = document.getElementById("submitBtn");
let displayOutput = document.getElementById("outputName");


submitButton.onclick = function(){
    const enteredUsername = usernameInputField.value;
    if(enteredUsername === "Rodney" || enteredUsername === "rodney"){
        displayOutput.innerHTML = enteredUsername + " access denied";
        
    }
        
    else if(enteredUsername === "Alexander" || enteredUsername === "alexander"){
        displayOutput.innerHTML = enteredUsername + " access granted";
        
    }
    else{
        displayOutput.innerHTML = enteredUsername + " not defined";
    }

}

Answer №2

One potential problem lies within the 'submit' function where it checks for an empty value. To address this, after the user clicks the button, make sure to retrieve the latest input from the user and compare it within the if-else block.

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

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {}); I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign ...

HTML and Javascript Form Integration for Sage Pay Purchase Button

Currently, I am working on a project that includes online payment options via PayPal and Google Wallet, with a "buy now" button. Now, my next step is to incorporate the Sage Pay "buy now" button onto the website using HTML and JavaScript. Although I have ...

The Power of ReactJS Spread Syntax

Currently working with React. In the state, I have an array of objects. this.state = { team: [{ name:'Bob', number:23 }, { name:'Jim', number:43 }] } My issue arises when attempting to create a copy of the arr ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

ASP.NET - The Power of a Long Press

I am currently working on implementing a Long Press event in JavaScript on an ASPX page. Due to my limited experience with JavaScript, I am facing a few challenges. I found a similar question that was previously asked here. When running the code, I encoun ...

What could be causing my directive to not display the String I am trying to pass to it?

Currently attempting to create my second Angular directive, but encountering a frustrating issue. As a newcomer to Angular, I have been studying and referencing this insightful explanation as well as this helpful tutorial. However, despite my efforts, I am ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this: |- main.js |- app.js |- /subapp1 |- subapp1.js |- subapp1.router.js |- /subapp2 |- subapp2.js | ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

Tips for personalizing and adjusting the color scheme of a menu in ant design

I am currently working on a website using reactJs and ant design. However, I have encountered an issue with changing the color of a menu item when it is selected or hovered over. Here's the current menu: Menu Image I would like to change the white col ...

Looking for guidance on implementing a straightforward nested for loop in a Node.js environment

I am facing an issue with my code that is meant to generate a 10x10 grid. Since transitioning to Node.js, I am struggling to make it work correctly due to my synchronous thinking pattern. Currently, the Y values are being assigned directly to 10 for all X ...

The React component does not trigger a re-render

Using React Redux, I am able to pass values successfully. However, the component I intend to render only does so once. Interestingly, when I save my code in VSCode, it renders again and the data displays on the page as expected. return ( <div classN ...

Get rid of numerous div elements in a React.js application with the help of a Remove button

I need help figuring out how to efficiently remove the multiple div's that are generated using the add button. I am struggling to grasp how to pass the parent div's id into the delete method from the child div. Additionally, I'm wondering if ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Utilize AngularJS to create a custom tag with a directive included

I've been working on creating a custom tag for a reusable component in a web page, but I seem to have hit a roadblock. It's not functioning as expected, and I feel like I might be overlooking something. If anyone could provide some guidance or p ...

What significance does it hold when an unhandled rejection event lacks a reason field?

Our app tracks client-side errors using Rollbar, but we keep encountering a not very helpful error message from Safari and Chrome: [unhandledrejection] error getting `reason` from event Upon investigation, I found that this message is generated by Rollbar ...

Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the f ...