The IF ELSE Statement will consistently evaluate as true when the first IF condition is met

I am currently working on implementing an IF ELSE statement in JavaScript to change the source image of a picture when a button is clicked. The idea is that when a user clicks on a specific body type button for a car, it will update the background image within three existing buttons. Upon clicking one of those buttons, the image source should change accordingly.

Unfortunately, every time I test the code, it only displays the picture associated with the first IF statement. I could really use some assistance with this issue, especially since I am still in the process of teaching myself JavaScript.

HTML

<div id="vehicleModelFrame">
    <button id="modelFrameButton1" type="button"></button>
    <button id="modelFrameButton2" type="button"></button>
    <button id="modelFrameButton3" type="button"></button>
</div>
<div id="selectTrimTitle">
    <h3>
        Vehicle Trim
    </h3>
</div>
<div id="vehicleTrimFrame">
    <div class="trimSelector">
        <ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#home">Trim 1</a></li>
            <li><a data-toggle="tab" href="#menu1">Trim 2</a></li>
            <li><a data-toggle="tab" href="#menu2">Trim 3</a></li>
            <li><a data-toggle="tab" href="#menu3">Trim 4</a></li>
        </ul>
        <div class="tab-content">
            <div id="home" class="tab-pane active">
                <img id="carLogo1" src="" alt="carLogo">
            </div>
            <div id="menu1" class="tab-pane">
                <img id="carLogo2" src="noimage.png" alt="carLogo">
            </div>
            <div id="menu2" class="tab-pane">
                <img id="carLogo3" src="noimage.png" alt="carLogo">
            </div>
            <div id="menu3" class="tab-pane">
                <img id="carLogo4" src="noimage.png" alt="carLogo">
            </div>
        </div>
    </div>
</div>

JAVASCRIPT

document.getElementById("modelFrameButton1").addEventListener("click", function showTrim1(){
    var carImg = document.getElementById("carLogo1");
    var backImg = document.getElementById("modelFrameButton1");

    if (document.getElementById("modelFrameButton1").style.backgroundImage = "JeepWrangler.png") {

        carImg.src = "Jeep_Wrangler.png";

    }else if (document.getElementById("modelFrameButton1").style.backgroundImage = "BMW3.png") {

        carImg.src = "BMW3.png";

    }

In order to better understand JavaScript, I am looking for solutions that are based on JavaScript principles.

Answer №1

Instead of using the assignment operator =, make sure to utilize the equality operator ==.

Assignments in this scenario result in a truthy string being returned, so be cautious of the distinction between the two operators.

Answer №2

During your testing, you attempted to check if the background image of document.getElementById("modelFrameButton1") is equal to "JeepWrangler.png", however, by using a single equals sign, you inadvertently assigned the value instead of comparing it. To rectify this, replace the = with === for non-type coercing equality checking. While in some situations you may opt for == for type coercing equality, it's generally advised to use === as it provides more accurate results (type coercing equality can lead to unexpected behavior).

Answer №3

The reason for this issue is that you are setting the value, not verifying it:

backgroundImage = "JeepWrangler.png"

It should be:

backgroundImage === "JeepWrangler.png"

Furthermore, your else if condition will not work as intended:

else if (document.getElementById("modelFrameButton1").style.backgroundImage = "BMW3.png")

It should be:

else if (document.getElementById("modelFrameButton1").style.backgroundImage === "BMW3.png")

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

Using Vue.js to apply different CSS classes based on multiple conditions

Is there a way to highlight rows in a table based on specific conditions? For example, when the fine is greater than zero (fine > 0) or the due date is later than today. The current code works well for highlighting rows where issue.fine is greater than ...

Maintain the dropdown selection while the table is being updated

My table updates every few seconds and each row has a dropdown menu that allows users to take actions on that row. However, the problem is that when new data is received from the database, the dropdown menu closes if it was open. This can be frustrating f ...

Tips for achieving the Bootstrap 5 Modal Fade Out effect without using jQuery or any additional plugins apart from Bootstrap

I'm facing some challenges in achieving the fade out effect in Bootstrap 5 modals. I am aiming for something similar to the "Fade In & Scale" effect demonstrated here: https://tympanus.net/Development/ModalWindowEffects/ It is crucial for me to accom ...

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

Tick the box to activate the ability to uncheck multiple boxes when there are already a certain number of boxes checked

I am currently developing a multiple-choice form in my MVC5 app and I am struggling to find a way to disable unchecked boxes once a specific number of boxes have been checked. For example, if 3 out of 5 boxes are checked, the remaining 2 should be disabled ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

Encountering a TypeError while attempting to sort in ReactJS: "0 is read only."

Every time I attempt to sort an object before mapping it in reactjs, I encounter the TypeError: 0 is read only. Despite trying to handle cases where props are empty or when the array length is more than 0 before applying the sort function, the error persis ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

The Express.js feature "app.use() mandates the use of middleware functions"

Currently, I am delving into learning Express.js 4 and Node, but I seem to have hit a roadblock with an error that has me stumped. I'm attempting to utilize the node-sass package to compile my sass code; however, I've encountered obstacles in ge ...

JS: Modifying this function to manage a click on a hyperlink

After following the guide provided here I have successfully implemented a drop down list that sends the value to an external PHP script, retrieves HTML output, and displays it in a "div" on the same page. It works flawlessly. My next objective is to send ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

When the search button is clicked to find a specific address, the React Google Maps API fails to zoom in on

How can we modify this code to achieve the functionality where, upon clicking the search button, the map zooms in closer to the address entered by the user, similar to how it works on Google Maps? The goal is to replicate the search feature from the Goog ...

(Express JS) What is the correct way to integrate another module into my router? (I am consistently encountering an undefined reference error)

I am currently working on a basic PDF reader application that utilizes the pdf.js library from Mozilla. The user is expected to select a file, after which the website should automatically redirect to the /reader page displaying the PDF. However, I am facin ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. https://i.sstatic.net/W7Fzi.png Issues with animation arise when you click the "Start" button again. The animation resets and begins ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...