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

Adjust the background of the input range style prior to the thumb icon

Is there a way to style the bar before the thumb with a different color on a range input? I have been searching for a solution without much success. This is the desired look: Unfortunately, Chrome no longer supports input[type='range']::-webkit- ...

Customize your Google Translate experience by choosing your own option values

Is there a way to trigger the same JavaScript calls by clicking on an option value in an HTML select element as with text-based links in the Google Translate widget? Check out this jsfiddle for more information <html> <body> <select i ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

Problem with vueJS List Transition not being triggered

Within my Vue JS App, I encountered a situation where I have a list of items that change order randomly when the user clicks a button. Despite successfully using Vue.set to dynamically reposition the list elements, I faced an issue with adding a transition ...

Is there a way to use SCTP with Socket.io and Node.js?

I have a new project in the works, creating a web application that will utilize web sockets to provide real-time updates for users. The plan is to seamlessly transmit changes from the back-end engine. My challenge lies in Node.js not supporting SCTP sock ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

Dynamic Select Box with Display of 2 Buttons

Looking to create an Ajax combo box with options for Female and Male. I would like to display a button for Female and a button for Male. Here is the code that I have: <!DOCTYPE html> <html> <head> <style> #for-male, #for-female{ ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

Does shouldComponentUpdate returning `true` have the same effect as not having shouldComponentUpdate at all?

Within my React Native component, I have included a blank shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { } I am aware, from reading this answer, that an empty shouldComponentUpdate function helps in eliminating unnecessary re ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

When using <body onload=foo()>, the function foo will not be executed

Having trouble with this code - it seems like initialize() is not being called. Check out the code here Any insight into why this might be happening? ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

Is there a way to extract subtitles from a javascript-controlled webpage using Python?

I am attempting to scrape information from this website: Link to Website Specifically, I am trying to extract the title ''Friday Night Lights'', but I am encountering difficulties accessing it due to JavaScript on the site. To achieve ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

Utilize npm to construct a Vue application and execute it on a Raspberry Pi device

My roommate and I are currently working on a Vue app project together, and we're aiming to deploy it on our Raspberry Pi. We're wondering if there's a way to npm build the final app on our PC and simply start the server on the Pi without hav ...

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...