Unable to assign a value to a variable in JavaScript

Today, I delved into the world of JavaScript and decided to test my skills by creating a page that changes images when clicking on a div. Everything worked perfectly until I wanted to add an input element to specify how many steps to jump each time the button is clicked. While trying to implement this feature, I noticed that the variable seemed to be accumulating values when I checked it through console.log. The first code snippet works flawlessly with fixed values, but the second one fails to function as expected. The aim was for the second code to dynamically change the colors based on the user-defined step size. However, this did not pan out as planned.

Check out the functioning code here

window.onload = function(){
        var x = 0;
        document.getElementById("teste").onclick = function(){myFunction()};
        function myFunction(){
            if (x == 0){
                document.getElementById("teste").style.backgroundColor = "red";
                document.getElementById("taiga").style.opacity = 1;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += document.getElementById("number").value;
            } else if (x == 1){
                document.getElementById("teste").style.backgroundColor = "blue";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 1;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += document.getElementById("number").value;
            } else if (x == 2){
                document.getElementById("teste").style.backgroundColor = "yellow";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 1;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += document.getElementById("number").value;
            } else if (x == 3){
                document.getElementById("teste").style.backgroundColor = "purple";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 1;
                x += document.getElementById("number").value;
            } else if (x == 4){
                document.getElementById("teste").style.backgroundColor = "black";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 1;
                document.getElementById("moge-ko").style.opacity = 0;
                x = 0;
            }
            console.log(x);
        };
    };

Check out the non-functioning code here

window.onload = function(){
        var x = 0;
        document.getElementById("teste").onclick = function(){myFunction()};
        function myFunction(){
            if (x == 0){
                document.getElementById("teste").style.backgroundColor = "red";
                document.getElementById("taiga").style.opacity = 1;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += 1;
            } else if (x == 1){
                document.getElementById("teste").style.backgroundColor = "blue";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 1;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += 1;
            } else if (x == 2){
                document.getElementById("teste").style.backgroundColor = "yellow";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 1;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 0;
                x += 1;
            } else if (x == 3){
                document.getElementById("teste").style.backgroundColor = "purple";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 0;
                document.getElementById("moge-ko").style.opacity = 1;
                x += 1;
            } else if (x >= 4){
                document.getElementById("teste").style.backgroundColor = "black";
                document.getElementById("taiga").style.opacity = 0;
                document.getElementById("nanachi").style.opacity = 0;
                document.getElementById("azami").style.opacity = 0;
                document.getElementById("kcalb").style.opacity = 1;
                document.getElementById("moge-ko").style.opacity = 0;
                x = 0;
            }
            console.log(x);
        };
    };

How can I modify the second piece of code to make it work as intended?

Answer №1

Within your code snippet, there is:

x += document.getElementById("number").value;

This means that you are instructing the variable "x" to add the value from your input field, treating it as a string. For instance, if the input has the value "1" and "0" is initially stored in your variable "x".. If you proceed with this code, the resulting value after the operation will be:

x += document.getElementById("number").value;

Resulting in: 01 whereas, what you actually desire is: 1

This mismatch occurs because you are adding a string type to an integer type variable.

To address this issue, you should parse the input value into an integer using parseInt():

x += parseInt(document.getElementById("number").value);

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

Ways to retrieve content from a website

After conducting thorough research on this matter, I stumbled upon an answer here. Despite following the provided solution, the process is still not functioning as expected. My goal is simple - to extract text from a webpage like Google and convert it into ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

Having trouble rendering a dynamic table with JavaScript utilizing a JSON object

I am struggling to retrieve data in JSON format and display it in a table. Despite trying various methods, I have been unable to make it work. Below is the code for this function. Can someone please assist me in identifying what is wrong with it? As of now ...

ng-class: Issue detected - The symbol '-' is positioned at column {2}

I'm having an issue with ng-class. I need to add a disabled state class if the role has admin privileges, but I keep getting an error. Here is the HTML: <label class="toggle modal-label-box" ng-class="{state-disabled: checkCanModify()}"> &l ...

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...

The intended 'this' keyword is unfortunately replaced by an incorrect '

Whenever the this keywords are used inside the onScroll function, they seem to represent the wrong context. Inside the function, it refers to the window, which is understandable. I was attempting to use the => arrow notation to maintain the correct refe ...

Echoing data from an input form is not possible with an associative array

I'm having trouble printing the associative array after inserting data from an input box. Currently, I can only display the latest data entered in the input box. What I really want is to continuously add data to the array and display it every time new ...

What is the reason behind the lack of collapsing in an inline-block container that only contains floated items?

Within this design, there are 3 boxes arranged in a row using the float: left; property for each one. These boxes are contained within 2 other elements. Typically, these containers collapse due to the content being comprised of floated items. However, chan ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Issues with SQL query execution in PHP with mySQL causing no results to be returned

$sql="SELECT * FROM Users WHERE '$searchType' = '$search'"; searchType represents the column and search is the specific value I am looking for. After confirming that my form is correctly submitting the values, I encountered an issue w ...

What is the process for utilizing jQuery's advanced ticker feature to extract content from a text file?

I am currently implementing this code on my website: <script> var file = "http://newsxpressmedia.com/files/theme/test.txt"; function getData(){ $.get(file,function(txt){ var lines = txt.responseText.split("\n"); for (var i = ...

What is the best method to extract and manipulate data from a JSON file in an AngularJS application?

personManagerInstance.getString("firstname",'common','en') I am currently passing a direct string in the UI which is affecting it. What I actually need is to read the data from a JSON file and return it as a string. personManagerInstan ...

Making lightbox/dhtml appear in front of flash

After extensive research, I have come across numerous posts highlighting the importance of modifying the embed-tag with wmode="opaque" in order to force lightbox and other dhtml elements above flash content. Simply adjusting the z-index of the desired elem ...

Vanilla JavaScript Troubleshooting: Top Scroll Button Issue

Attempting to develop a Scroll To Top Button utilizing Vanilla JS, encountering errors in the dev console. Existing jQuery code that needs conversion to vanilla js Uncaught TypeError: Cannot read property 'addEventListener' of null My Vanilla ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

Leverage the PhantomJS variable within the page.evaluateJavaScript function

Currently, I am using PhantomJS to capture a screenshot of the dashboard and save it as a PNG file. Everything works perfectly fine until I try to include additional arguments (line, dFrom, dTo) and use them within the page.evaluateJavaScript() function. U ...

What are the steps to implement a Bottom Navigation bar in iOS and a Top Navigation bar in Android using NativeScript Angular?

For my project, I decided to utilize the tns-template-tab-navigation-ng template. I am currently working on creating a WhatsApp clone, and in iOS, it features a bottom navigation bar while in Android, it has a top navigation bar. I am looking for guidance ...