The JavaScript else statement is failing to execute as intended

Hello, I am new to JavaScript and could really use some assistance.

In the code snippet below, I am having trouble with the logic for the submit button. The line _btn.addEventListener seems to be causing an issue where only the "if" part is being executed, and there seems to be a problem with the condition in the "else" part. Even when the date and image are clicked, only the alert from the "if" condition is being displayed.

<p align=center>
        <input type="submit" value="submit" id="button">
    </p>


 <script type="text/javascript">
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _picker = document.getElementById("picker");
let _btn = document.getElementById("button");

let isImgClicked = false;
let isDatePicked = false;

_img.addEventListener("click", function(){
  isImgClicked = true;
});
_picker.addEventListener("click", function(){
  isDatePicked = true;
});
_btn.addEventListener("click", function(){
if(!isImgClicked || !isDatePicked) {
alert("Please select a year and click on the car image");
} else {
// logic for redirecting based on image and date selection
}
});
</script>

Answer №1

In this code snippet, you are setting the variables isImgClicked and ImgClicked to true when an image is clicked.

img.addEventListener("click", function(){
  isImgClicked = true;
  ImgClicked = true;
});

However, later in the code, you are comparing these boolean variables with strings, which is not correct.

if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))

To fix this issue, make sure to compare boolean variables with boolean values or convert them to strings before comparison.

Answer №2

Your code has been refactored to use early-return style:

function() {
    if(!isImgClicked || !isDatePicked) {
        alert("Please select both the Year and click on the car image");
        return;
    }

    if((isImgClicked == "_img") && (isDatePicked == "DatePicked")) {
        window.location.replace("sample1.html");
        return;
    }

    if((isImgClicked == "_img") && (isDatePicked == "DatePicked1")) {
        window.location.replace("sample2.html");
        return;
    }

    if((isImgClicked == "_img1") && (isDatePicked == "DatePicked")) {
        window.location.replace("sample3.html");
        return;
    }

    if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1")) {
       window.location.replace("sample4.html");
       return;
    }

    alert("Invalid selection!");
}

Which specific if statement are you struggling with?

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

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

Decide whether Variable Name is equal to the String

I am currently facing an issue. var myArrayVariable1 = new Array(); var myStringVariable1 = 'myArrayVariable1'; var myStringVariable2 = 'myArrayVariable2'; Is there a way to determine if one of the strings matches the variable name? F ...

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

Div that adjusts according to the width of an image

I have some images of a laptop and a tablet displayed on my webpage. The issue I am facing is that the div above the laptop should always match the width of the laptop. Everything looks great at full width, but problems arise when I scale down the window s ...

Step-by-step guide on redirecting a page from a Django form

I'm in the process of developing a dictionary application that allows users to input a word through a form. The issue I'm facing is that when a user enters a word and hits submit, the form disappears leaving only the submit button and the search ...

Is it possible to eliminate any leftover comments from a JSON string using jQuery and Ajax?

Having an issue with a framework that generates invalid JSON String like this: /* { "myobject" : "test"} */ The problem lies in the comments before and after the json string. This is done for security purposes, as it's not recommended to return JSON ...

Deleting object property within Angular ng-repeat loop

I have information structured like this: $scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1}, "5": {"cost": 802.85, "description": "test", "qty": 1}}; My goal is to iterate through this data and show it with a remove button. How can I s ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

What is the process for linking a specific HTML file to a URL?

After preparing all my HTML, CSS, and JS files for upload to a server (I am using cPanel which I have experience with), I found myself wondering how to assign a specific HTML file to a custom link, such as "devwebdevelopment.com/about" I am looking to cre ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...

Experience seamless navigation with Highstock's fluid panning feature

I'm attempting to achieve seamless panning on a basic highstock chart by clicking and dragging within the plot area. Interestingly, I have found that this works flawlessly when my data is not based on timestamps: data: [-25.1,-23.8,-19.9,-19.1,-19.1 ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

What strategies can be employed to maintain reliable datetime management for a reservation system operating in diverse time zones?

Looking at the big picture: An interesting scenario arises when a hotel owner specifies a time frame for booking reservations at a restaurant (5pm - 10pm). Along with this information, there is also a timezone provided to ensure that dates are displayed i ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

Passing data from a child component to a parent component in Vue 3: How

Struggling with Vue 3 app authentication through event-emission from child to parent. Below is a snippet of the code: Child <template> <form class="msform"> <input @click="goToLogin" type="button" name=&q ...

Shifting the entire page from left to right and back again

I am in search for a template that moves the page from left to right. If anyone can guide me on how to create this effect or provide a JavaScript example, I would greatly appreciate it. ...

What could be the reason for the undefined value of my ID retrieved from the next JS router.query upon page refresh?

When using the id obtained from the next router.query to dynamically render elements, it works fine when accessing the room from next/link. However, upon refreshing the page, an error is thrown. https://i.stack.imgur.com/yEjGS.png Below is the code snipp ...

cheerio scraping results in an array that is devoid of any data

Struggling to extract data from a website with the URL https://buff.163.com/market/csgo#tab=buying&page_num=1 using request-promise and cheerio. Check out my code snippet below: const request = require('request-promise'); const cheerio = requ ...

Steps to open specifically the WhatsApp application upon clicking a hyperlink, image, or button

I need a code for my HTML website that will open the WhatsApp application when a user clicks on a link, image, or button while viewing the site on a mobile device. Only the WhatsApp application should be opened when a user interacts with a link on my webs ...