I am attempting to create a password validation system without the need for a database, using only a single

Help Needed: Trying to Create a Password Validation Website

<script language="Javascript">
  function checkPassword(x){
    if (x == "HI"){
      alert("Just Press Ok to Continue...");
    } else {
      alert("Nope... not gonna happen");
    }
  }

  var grape = alert("Just press Ok to Countinue...")

  function redirectToWebsite() {
    if (grape === true){
      window.location="http://www.google.com";
    } else {
      alert("Nope... not gonna happen")
    }
  }

}
</script>

<center>
<br /><h3>Please Enter the Password</h3>
<br />
<b>Password:</b>
<input type="password" id="pass" value="">
<br /><br />
<button onclick="javascript:checkPassword(document.getElementById('pass').value)">Check Password</button>
<button onclick="javascript:redirectToWebsite">Proceed To my Website</button>

I would appreciate any help as I am still learning JavaScript and prefer not to use PHP. Thank you!

Answer β„–1

apple will be equal to null.

The reason for this is that alert() consistently yields null (does not have a return value).

It is advisable to utilize confirm() instead.

Answer β„–2

Your code faces a major issue where you have two functions attempting to achieve the same goal. The second function, alertIt, is based on a condition that will never be true.

Let's address these issues individually...

  1. To start with, there is an extra } just before the closing </script> tag. This mistake means none of your code would run at all. Hopefully, this was just an oversight during copying and pasting.
  2. The line:
    var grape = alert("Just press Ok to Countinue...")
    will always make grape equal to undefined because an alert() doesn't return any value. Consequently, the condition if (grape === true){ in your alertIt function will never evaluate to true.
  3. Perhaps the most critical issue is that your code is overly complex for the simple task you mentioned: validating a specific password and redirecting the user to your website if correct. In reality, you only need the check function. You can eliminate the alertIt function and the button to proceed onto your website.
  4. While not directly related to the functionality problem you faced, it’s worth noting that using inline HTML attributes like onclick, onmouseover, etc., creates global anonymous wrapper functions, leading to complicated code that hinders scaling and debugging. It is advisable to adhere to W3C DOM Event standards instead.
  5. Lastly (though again unrelated to the main issue), styling should be handled by CSS rather than employing deprecated HTML elements like <center>.

With necessary adjustments, your working code now appears as below. Please review the comments within the code for clarifications on each step:

// After the DOM has loaded:
window.addEventListener("DOMContentLoaded", function(){

  // Obtain references to required elements
  var password = document.getElementById("pass");
  var btnPassword = document.getElementById("btnCheck");

  // Avoid linking HTML elements to JavaScript event callbacks directly in HTML
  // Instead, use .addEventListener() following W3C DOM Event standards
  btnPassword.addEventListener("click", function(){
    // Invoke the check function with the password
    check(password.value);
  });

  // Simplified function combining the previous "alertIt" and "check"
  function check(x){
    if (x == "HI"){
      // Notify the user and progress if the password is correct
      alert("Just Press Ok to Continue...");
      window.location="http://www.google.com";
    } else {
      // Inform the user otherwise
      alert("Nope... not gonna happen");
    }
  }
  
});
/* Define style rules affecting specified parts of the document */
body { text-align:center; }
#pwd { font-weight:bold; }
<!-- Notice that <center> and <b> have been transferred to the CSS
     as formatting should not belong in HTML. Additionally, <div> and <p> were added for structure while excessive <br> tags were removed. Remember not to use HTML for styling purposes.                  -->
<div>
  <h3>Enter the Password</h3>
  <br>
  <span id="pwd">Password:</span>
  <input type="password" id="pass">
</div>
<p>
  <button id="btnCheck">Check Password</button>
</p>

Answer β„–3

While this code is helpful for learning purposes, it's important to note that sensitive information like passwords can easily be viewed by anyone with access to the source code. Therefore, it's recommended to use this code solely for educational purposes. I have stripped away any additional complexity so we can focus on the main question at hand. Once you address all the issues pointed out by @ScottMarcus and other contributors, your final code should resemble something similar to this...

function check(x) {
  if (x === "HI") {
    alert('going to website')
    location.assign("#mywebsite");
  } else {
    alert("Nope... not gonna happen");
  }
}
<h3>Enter the Password</h3>
<b>Password:</b> 
<input type="password" id="pass" value="">
<button onclick="javascript:check(document.getElementById('pass').value)">Check Password</button>

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

JavaScript code for the submit button to proceed or halt the form submission

Within my JSP file, I have the following code snippet: <input type="submit" value="Transfer ULD" onclick="doSomething();" name="_eventId_transferULDTransition"/> The doSomething() function mentioned above is a JavaScript method. function doSomethi ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

What steps can be taken to resolve a Mediasoup installation error in a Node.js environment?

While attempting to install the mediasoup library, I ran into an error that has me stumped. If anyone has encountered this issue before or knows how to solve it, any assistance would be greatly appreciated. > <a href="/cdn-cgi/l/email-protection" c ...

Enable arrow keys feature in Regular Expressions

Currently, I am implementing alphanumeric validation to ensure that users can only input alphanumeric values and also paste alphanumeric values exclusively. In order to achieve this, I have utilized the following regular expression: function OnlyAlphaNum ...

Employing JavaScript for fading divs in and out sequentially

Hey there! I'm currently struggling with implementing transitions for my tool tips. Any assistance would be greatly appreciated! I am looking to have my "fader" divs fade in and out on click of a button, with each transition lasting 5 seconds. It&apo ...

Error: The Gravatar service is unable to retrieve the property 'get' from an undefined source

I have a basic app with just one controller. I'm trying to debug the output of the Gravatar.get() function in the console. However, I encounter an error saying: "TypeError: Cannot read property 'get' of undefined". I'm confused because ...

The continual appearance of "No file found" persists when utilizing the $redirectRoute

My goal is to make one of the links on my website lead to another page within the site. Below is one of the two links found on my index.html page: <html ng-app="myApp"> . . . <body> <h1>My Home Page</h1> ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...

Tips for working with elements in WebDriver that are created dynamically by JavaScript

As a novice in automation using Java and WebDriver, I find myself facing a particular issue: Browse for a specific customer Select a new customer type from a dropdown menu Click on the Save button Outcome: Upon trying to change the customer, a message p ...

Retrieving various pieces of data in Express

After scouring through various websites, I am still unclear on how to extract multiple GET variables using Express. My goal is to send a request to a Node.JS Express server by pinging the URL with: file_get_contents('http://127.0.0.1:5012/variable1/v ...

Obtain the initial Firebase child element without a specific key

Trying to access the first child of a firebase object is my current challenge. The reference is structured as follows: var sitesToVisitRef = firebase.database().ref('sitesToVisit') The reference is confirmed functional as I am able to write to ...

Working with external data in D3.js involves loading and manipulating datasets efficiently

As a newcomer to D3.js, I have been exploring various tutorials and exercises to familiarize myself with it. My primary goal with D3 is to load external data, typically in JSON format, and create interactive charts based on that data. You can find the bas ...

Do you have any suggestions on how to fix this npm SQLite installation issue?

Could use some help with an SQLite installation error I'm encountering. Any ideas on what the issue might be and how to resolve it? C:\Users\jacka\Downloads\discord-emoji-stealer-master\discord-emoji-stealer-master>npm i & ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...

The www file is only loaded by Node Inspector when the preload setting is turned off

Whenever I start node-inspector The node-inspector browser window successfully loads all the files. https://i.sstatic.net/Ctx2K.png However, when I use node-inspector --preload=false Only my bin/www file is loaded on the node-inspector window. http ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

What is the best approach to managing a standard form in React without utilizing AJAX?

Trying to access an endpoint https://api.com/signup.ashx is causing CORS issues. I have been instructed to make the API call without using axios or fetch. Here's what I attempted: const handleSubmit = async (event) => { let error = false ...