What is the reason for this code failing to verify the authenticity of the passcode?

The validation process is not functioning properly and there seems to be a missing alert dialog box. I would like the passcode entered by the user to be compared with the constant "Pass".

const Pass = '2207'

function checkValidity() {
  const pass_code = document.getElementById("passcode").value;
  if (pass_code == Pass) {
    alert("Correct Passcode!");
  } else {
    alert("Wrong Passcode!");
  }
}
<div id="display">
  <p style="color:black">Enter your Passcode:</p>
  <input id="passcode" type="password">
  <button onclick="checkValidity()">Enter↵</button>
</div>
<script src="script.js"></script>

Answer №1

checkValidity is a predefined method, which means that your function is being overshadowed by it and not executing as expected. To resolve this issue, there are two possible solutions - one that simply works and another that is considered superior.

The first solution involves renaming your function to avoid conflicts with the existing method.

The second solution entails refraining from using inline attribute assignment to handle events, opting instead for addEventListener. Not only does this approach provide various advantages (refer to References), but it also ensures smooth functioning of the code snippet provided below:

const pass = '2207'

const button = Array.from(document.getElementsByTagName("button"))[0];
button.addEventListener("click", checkPassword);

function checkPassword() {
  const pass_code = document.getElementById("passcode").value;
  if (pass_code == pass){
    alert("Correct Passcode!");
  }

  else{
    alert("Wrong Passcode!");
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body style="background-color: rgb(0, 255, 195); text-align: center">
  <div id="display">
    <p style="color:black">Enter your Passcode:</p>
    <input id="passcode" type = "password">
    <button>Enter↵</button>
  </div>
  <script src = "script.js"></script>
</body>
</html>

1 The statement suggesting that checkValidity is a reserved word has been corrected by Jaromanda.


P.S. It is advisable to refrain from using inline styling and instead opt for internal or external CSS according to best practices.

P.S. 2 Additionally, following established conventions, variable names should not begin with a capital letter unless they denote a class or constructor.

References

Answer №2

Despite what two answers may claim, the term checkValidity is not a reserved word in javascript.

Consider this scenario:

// here's a simple checkValidity function
function checkValidity() {
  console.log("I am global");
}

// consider function x as the execution context of `onevent="...."`
function x() {
  function checkValidity() {
    console.log("I am inside x");
  }
  // think of this as the function called in `onclick="checkValidity()"`
  checkValidity();
}
x();

No wonder the output is I am inside x. If this concept is unclear to you, I recommend understanding why this behavior occurs.

When using

onclick="checkValidity()"
(in this specific situation), the execution context of checkValidity() causes the method checkValidity belonging to an instance of HTMLButtonElement to be invoked, rather than your globally declared function with the same name.

  • The simplest solution is to use a function name that doesn't overlap with a method name of HTMLButtonElement in both the onclick attribute and your javascript code
  • An alternative solution is to use
    onclick="globalThis.checkValidity()"
    while keeping the javascript function unchanged
  • The best modern practice, in my opinion, is to utilize addEventListener to prevent such issues from arising initially. This way, you have flexibility in naming your functions without conflict.

Answer №3

One issue is that you have chosen a reserved word as the name for your function. I changed the function name and it worked successfully.

function verifyValidity(){
    console.log("testFunction");
    const pass_code = document.getElementById("passcode").value;
    if(pass_code === pass){
        alert("passcode is correct!");
    }
    else console.log("passcode is incorrect!");
}

Another concern is the use of a capitalized P for the Pass variable. It is recommended to use a lowercase p when naming variables. Additionally, make use of '===' instead of '==' because it compares types as well (even though both are strings in your case, it's good practice to use '==='.)

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

Photos appearing outside the border

My current border has a vertical flow like this: https://i.sstatic.net/CdUm6.png (source: gyazo.com) However, I want the content to flow horizontally from left to right instead of top to bottom. When I apply float: left; to the controlling div, it resu ...

Eliminate (strip away logos) specific HTML code from webpage without the use of JavaScript or CSS

The specific code that needs to be removed is: <p style="text-align:center;">Created by <a href="http://www.fancywebsite.com" target="_blank">FancyWebsite</a></p> Maybe using PHP functions like str_replace() or trim() could do the ...

The inArray() function will always return a negative result

I'm encountering an issue and need some help resolving it - whenever I use inArray(), I consistently receive a value of -1. Here's a breakdown of what I'm trying to achieve : <!-- HTML Markup --> <nav class="navigation clearfix"&g ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Guide on utilizing jQuery to create a popup window for streaming Vimeo or YouTube videos

Currently working on the landing page design for a new iPhone app and thinking of incorporating a video modal window similar to the one on: . Came across this helpful thread on "Popup Jquery window to play youtube" but unsure how to resize the video to pr ...

JavaScript - array of dates, constructing links

I need help figuring out how to make the eventName a clickable link instead of just text. If I add a link directly in the code, it shows up as plain text. Is there a simple trick or do I need to create a new function for this? Any advice would be greatly ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

What is the best way to access the text content of a nested HTML element for automation tasks with Selenium or Protractor?

Can anyone help me with this HTML code snippet? I want to extract and display only the text within the desc class - "Print this", ignoring the text in the spell class. This needs to be done using either Protractor or Selenium. <span class="desc"> Pr ...

Using jQuery to create a fade in/fade out effect within a list of items

I'm currently experimenting with jQuery's fadeIn/fadeOut effects on images used as buttons within an unordered list. My goal is to have the hovered image fade in quickly and out slowly upon mouseout. The issue I'm encountering is related to ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

Tips for integrating custom images or icons into Onsen-UI:

I am currently utilizing the Onsen-UI framework along with AngularJS to create a mobile application. I want to incorporate custom images for buttons, but they appear blurry or unclear on certain mobile devices when the app is launched. Below is my code sn ...

React Router Blank Page Conundrum

In a new project, I'm experiencing an issue where the content is not loading in despite using a similar React-Route setup that worked in a previous project. When I create a nav link in the root directory, it changes the path but the screen remains whi ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

submit django form when a checkbox is checked

tml: <div id="report-liveonly"> <form action="." id="status" method="POST">{% csrf_token %} <p>{{SearchKeywordForm.status}}Only display LIVE reports</p> </form> </div> I am facing an issue while trying to submit ...

ng-repeat displaying an empty list

Currently, I am working on an AngularJS application where I am attempting to display data retrieved using the http get method from a RESTServer. The GET request is sent from one view and upon success, it navigates to another view within AngularJS. Both vi ...

verifying the user's screen dimensions

I'm currently exploring ways to customize the appearance of my website based on the viewer's screen resolution. I am interested in potentially optimizing the layout for vertical screens on mobile devices, and horizontal screens for laptops. Addit ...

Validation based on the condition of the request body in Express using express-validator

I have a specific route in place for handling different scenarios, with only minor variations in logic between them. To keep things streamlined, I have decided to utilize a single endpoint and differentiate between cases using the parameter 'type&apos ...

Nested foreign array elements found within an object's array structure

I have a collection of skills, here they are: var my_skills = ['problem solving', 'collaboration', 'public speaking']; There is also an object array in the mix: var jobs[0] = {title: "developer", skills:[my_skills[0], my_sk ...

Adjust the dimensions of the thead, tbody, and td elements on the fly

I've implemented this property in a .css file on the table shown below and there are 9 records. .fixed tbody td, thead th { width: 5.2%; float: left; } In my scenario, when there are 4 columns, the width should be 23.2%; for 5 columns ...

JavaScript: utilizing a conditional statement to return from a function enclosing another function that returns a promise

I am looking to encapsulate some logic within a function. This logic will involve evaluating the result of a promise and then either returning a value or throwing an exception based on a conditional evaluation of the promise. Here is a simplified version ...