Attempting to sum all numbers in a specified range by iterating through each number with a for loop

I'm having trouble understanding the problem with my code. The goal is to calculate the sum of every number in a given range (for example, entering 1 and 2 should output 3). However, when I input 1 and 3, the output unexpectedly becomes 12.

function Sum(){
        var int1=document.getElementById("TextBox1").value;
        var int2=document.getElementById("TextBox2").value;
        for(i=int1; i<=int2; i++){
            var total=int1;
            total+=i;
            if(i==int2){
                alert("The sum of all numbers is "+total);
            }
        }
}


        function Sum(){
        var int1=document.getElementById("TextBox1").value;
        var int2=document.getElementById("TextBox2").value;
        for(i=int1; i<=int2; i++){
        var total=int1;
        total+=i;
            if(i==int2){
                alert("The sum of all numbers is "+total);
            }
        }
        }

    

        <html>
        <head>
        <title>
        For Sum Exercise
        </title>
        </head>
        <body>
        <script>
        </script>
        User Number 1:<input id="TextBox1"><br><br>
        User Number 2:<input id="TextBox2"><br><br>
        <button onClick="Sum()">Sum</button><br>
        </body>
        </html>

    

Answer №1

To get a number from the input, use the value which is of type string and apply the unary plus +.

Make sure to declare the variable i.

Before entering the loop, initialize total with zero.

Calculate the result after completing the loop.

function Sum() {
    var int1 = +document.getElementById("TextBox1").value,
        int2 = +document.getElementById("TextBox2").value,
        total = 0,
        i;

    for (var i = int1; i <= int2; i++) {
        total += i;
    }
    document.getElementById("sum").innerHTML = "The sum of all numbers is " + total;
}
User Number 1: <input id="TextBox1"><br><br> User Number 2: <input id="TextBox2"><br><br>
<button onClick="Sum()">Sum</button><br>
<p id="sum"></p>

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 a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

Adding individual names for elements in a list using Jackson

Is there a way to assign a unique name to each element in a JSON list using JACKSON? For instance, consider the following JSON data: {"result": [ { "name": "ABC", "age": "20" },{ "name": "DEF", "age": "12" } ]} Howeve ...

Axios is not properly sending all form data to MongoDB when used with React and Express

While working on a project involving data transmission from an HTML form element in React to MongoDB using Express.js, I encountered an issue where only the last input value from the Form element was being sent. Surprisingly, the console displayed the last ...

What could be causing my express router.get endpoints with multiple paths to only render text?

Currently, I am in the process of configuring a password reset flow using Pug (formerly Jade) and Express. Oddly enough, GET requests that contain URLs with multiple appended paths are causing my Pug view files to render with only text. The images and sty ...

Simple solution to resetting class in an element upon clicking another element

Is there a way to reset the glyphicon of one column back to its original state when another column is clicked while sorting a table using bootstrap glyphicons? $('.tablePointer').click(function() { $(this).find('i').each(func ...

Mistakes in Sequelize

New to using Sequelize, I recently attempted to implement a currency system for a Discord Bot game that I am working on. While I may have structured the tables incorrectly, I believed this approach would be suitable for my needs. In addition to the core se ...

Understanding JavaScript JSON Object Parsing

$(document).ready(function () { var oOpenOrders = new Array(); $('#btn').click(function () { $.ajax({ type: 'GET', url: 'http://192.168.19.22/test.php', contentType: "applica ...

Tips for retaining form inputs without the need for a submit event when the page is reloaded or refreshed

I have a form on a page with multiple text inputs In addition to the form, I have implemented Zend pagination to allow users to select results. However, when using Zend paginate, the user's form inputs are lost because it is not submitted. Since th ...

Jquery not functioning properly for email validation

I've been working on an email validation function, but for some reason it's not working as expected. Do you have any suggestions on what might be causing the issue? Am I missing something in my code or should I consider restructuring it? This i ...

The react-native-swiper component is malfunctioning and the button functionality is not functioning

Problem Description The issue arises when the blue active button does not update properly while using the react-native-swiper. Specifically, the button fails to reflect changes as the swiper moves. This occurs when creating a view for the swiper utilizing ...

Resolving the issue of encountering 'Failed to load resource: the server responded with a status of 500' in React and express

Attempting to upload an image to a local folder using multer and React resulted in an Internal Server Error. The chrome debugger indicated that the server responded with a status of 500. It seems like the data format being sent to the server side is incorr ...

Is there a way to handle the ajax request only when necessary, instead of processing it every few seconds?

Currently, I am working on an AJAX chat system using PHP, MySQL, JavaScript, and AJAX. I have a piece of code that retrieves all chat messages within a div using AJAX, with the function running every 2 seconds. My issue lies in the fact that the div autom ...

Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using: <html> <head> <link type="text/css" rel="stylesheet" href="html.css" /> <script type="text/javascript"> function getName() { if(name) alert("Did y ...

Emphasizing Page Numbers with Repeater Control

In my program, I have implemented a repeater control with paging functionality. When clicking on a page number within the repeater, it gets highlighted in a different color which works correctly. However, there is also a "View all" button present. The issu ...

Challenges Ensuring Validation of Each Object in JSON Schema Using Postman

Despite its seemingly straightforward nature, I am encountering difficulties in fully validating JSON response data within Postman (Tiny Validator 4) when multiple objects are returned. During negative testing, I discovered that it only checks the first ob ...

Activate ng-show when there are updates to the JSON data

I'm currently working on a feature where I need to hide the upload button and display a new edit button once the user uploads a file. My project involves using both angular-file-upload and md-data-table libraries. To achieve this, I have implemented a ...

Failed to convert video to blob and upload it due to readAsArrayBuffer returning an empty array

Currently, I am facing an issue while attempting to upload a video using Ionic, Capacitor, and React. To achieve this, I have integrated the cordova-video-capture-plus plugin into my project. The problem arises when I try to execute the readAsArrayBuffer ...

Client component in Next.js is automatically updated upon successful login

I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side: export default async function R ...

finding it difficult to display my components when incorporating ROUTE in my ReactJS project

Can anyone help me with the code for app.js? I've been trying to implement ROUTE but my components are not rendering correctly. import './App.css'; import Home from './pages/Home'; import Rooms from './pages/Rooms'; impor ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...