In the conditional statement, document location or window location href will be ineffective in the if clause but will be functional in the else clause

When validating a password in a form, I have encountered an issue where the code only works for one specific outcome. If the correct password is entered, the user should be moved to site X, but if it's incorrect after 3 tries, they should be moved to site Y.

Unfortunately, the code seems to only redirect users to site Y regardless of whether the password is correct or not.

The code snippet being used:

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <form>
        Enter password to continue: <br>
        <input type="text" id="user"/>
        <input type="button" id="myButton" value="Enter site"/>
        </form>

        <script>
           let tries = 0;
                let error = 0;
            let password = 'tiesto';

            document.querySelector("#myButton").onclick = ()=> {
                let passwordValue = document.querySelector('#user').value;
                if (password === passwordValue) {
                    window.location.href = 'http://maariv.co.il';
                } else {
                    tries++;
                    alert('Try again please.');
                }

                if (tries === 3) { // 3 is the limit.
                    error++;
                }

                if (error === 1) {
                    window.location.href = 'http://microsoft.com';
                }
            };
        </script>
    </body>
</html>

I attempted the following solutions:

  1. Conducting thorough syntax error checks within the code.
  2. Changing === to == under the assumption that the quotation marks may impact equality comparisons.
  3. Testing
    window.location.href = 'http://maariv.co.il', true;
    .
  4. Including return false immediately after window.location.href.

As a novice, I am puzzled as to why the conditional statement seems to partially work - with the negative part triggering correctly while the positive outcome fails to execute as intended.

Update:

This scenario is solely for practice purposes and will not be implemented in a live environment. In a production setting, it would be necessary to securely store and validate passwords through database interactions.

Answer №1

Insert the line

let passwordValue = document.querySelector('#user').value;
inside the onclick event of "mybutton".

let attempts = 0;
let errors = 0;
let secretCode = 'tiesto';

document.querySelector("#myButton").onclick = ()=> {

    let inputPassword = document.querySelector('#passwordInput').value;

    if (secretCode === passwordValue) {
        window.location.href = 'http://maariv.co.il';
    } else {
        attempts++;
        alert('Please try again.');
    }

    if (attempts === 3) { // 3 is the threshold.
        errors++;
    }

    if (errors === 1) {
    window.location.href = 'http://microsoft.com';
    }
};
<form>
  Enter password to continue: <br>
  <input type="text" id="user" />
  <input type="button" id="myButton" value="Enter site" />
</form>

Answer №2

When dealing with password validation, always remember to use the 'return' keyword:

if (password === passwordValue) {
    return window.location.href = 'http://maariv.co.il';
}

In case the password is incorrect, the function will continue executing until it reaches a second redirection, which will take precedence over the first one.

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

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

Tips for incorporating css @keyframes within a cshtml file:

My cshtml page includes a Popup that I created, but I encountered an issue with keyframes. When I tried to use it without keyframes, the fade effect was lost. I am looking for a way to fix my @keyframes. (I tested the code on Chrome and Opera) I found the ...

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...

Displaying data using JSON on a fabric.js canvas

I've been encountering some issues while attempting to store data in JSON and then reload it onto the canvas using fabric.js. My code is quite simple: canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 })); ...

The AJAX response is incorrect due to a PHP request, leading to the reloading

Whenever the 'signup' button is clicked, a function in my code initiates an HTML switch. The issue I am facing arises when I test for incorrect email or password during sign up. While I can successfully verify the data, it still loads the previou ...

Compare and contrast the functions of scrollToIndex and manual scrolling in a React Native FlatList

Currently, my FlatList is set up to automatically scroll item by item based on a time series using the scrollToIndex function. However, I also want to allow users to manually scroll through the list and temporarily pause the automatic scrolling when this ...

NodeJS allows for the dynamic import of modules, enabling a flexible

I'm currently developing a CLI package within a monorepo that contains a command called buildX. This command goes through various directories, attempting to use the require function to locate a module within certain files in those directories. In ess ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

Leveraging IE conditional comments for including CSS or JavaScript files can lead to an increase in the number of HTTP

Our web designer has implemented special pages for Internet Explorer by using IE-specific comments. This means that certain stylesheets are only loaded if the user is using a specific version of IE: <!--[if lt IE 7]> <link type="text/css" rel="st ...

Content that moves with a flick of a finger

Seeking advice on a widely used JavaScript library that can facilitate scrolling for frequently updated content, similar to what popular websites like have implemented. I've had difficulty finding the right query on Google, so any recommendations or ...

Do you typically define a static variable within a function using `this.temp`?

I am looking to implement a static variable within a function that meets the following criteria: It maintains its value across multiple calls to the function It is only accessible within the scope of that function Below is a basic example of how I am mee ...

I am having trouble getting my JavaScript to load

I've hit a roadblock trying to understand why my JavaScript code isn't executing properly. Could someone kindly point out what I may have overlooked? :( JSFiddle Link HTML Snippet <div class="po-markup"> <br> <a href="# ...

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

What is the best way to send the value of this variable through the parameters?

In jQuery: initializeSliders(socket, '!{requestData}'); requestData is a special object (an HTTP request object in my Express.js web application) that contains information such as my session. However, when I pass this object into the initialize ...

Building a straightforward RESTful API for user authentication with Node.js, MongoDB, and Express.js

Can someone provide guidance on creating a RESTful API using Node.js, Express.js, and MongoDB? Specifically, I am looking for assistance with writing the schema for login and sign up pages, as well as comparing data in MongoDB using Node.js Express.js. As ...

javascript basic image carousel

How can I modify my slider so that "slide 1" appears after "slide 3" without needing to use the return or previous button each time? I'm not very well-versed in javascript, so I thought I'd reach out for some assistance ...

Issues arise when attempting to transmit JSON data from JavaScript to the server using the POST method

I'm having trouble viewing the JSON data I sent to the server using XMLHttpRequest. It seems like the server isn't receiving it because when I run the JavaScript, the alert window pops up but doesn't display anything. Does anyone have a solu ...