Home > database >  Trying to use alert() to show sum of numbers from 1 to whatever number you put in
Trying to use alert() to show sum of numbers from 1 to whatever number you put in

Time:10-05

So the problem here is I need an alert box with my provided code in it to show up. I have tried a lot and it is still not showing what I want it to. I will also provide a picture of what I am looking to re-create.

Here is my code:

function sumOfNumbers() {
  var theNumber = document.getElementById("txtNumber").value;
  if (theNumber > 0) {
    var theSum = 0;
    for (var i = 1; i <= theNumber; i  ) {
      theSum  = i;
    }

    alert(
      "The sum of all the numbers from 1 to "   theNumber   " is "   theSum   ""
    );
  } else {
    alert("negative "   theNumber);
  }
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>

For some reason, my HTML tags on the top aren't showing. Here is what the box is supposed to look like:

intended output

When I click on the "calculate sum" button, nothing will even show. Any help is greatly appreciated!

CodePudding user response:

I've slightly altered your code to use an eventListener rather than an inline click handler. Your code had a few syntax errors (missing closing braces, misplaced else) that were causing the issues. I always find it helpful to use consoleLog when trying to debug, which is how I found those bugs.

let btn = document.querySelector('.btn');
btn.addEventListener('click', sumOfNumbers);

function sumOfNumbers() {
  var theNumber = (document.getElementById("txtNumber").value);
  if (theNumber > 0) {
    var theSum = 0;
    for (var i = 1; i <= theNumber; i  ) {
      theSum  = i;
    }
    alert('The sum of all the numbers from 1 to '   theNumber   ' is '   theSum   '');
   } else {
    alert(`invalid input. ${theNumber} is a negative number`);
  }
}
<input type='text' id='txtNumber'>
<button type="button" >Calculate</button>

CodePudding user response:

You can create an N array using [ ...Array(theNumber).keys() ] and then loop through and add like so

const sumOfNumbers = () => {
const theNumber = document.querySelector("#txtNumber").value;
if(isNaN(theNumber) || ( theNumber < 0))
{
return alert(`Not valid or negative number ${theNumber}`);
}
var numArray = [ ...Array( theNumber).keys() ];

let sum = 0;
for(let i = 0; i < numArray.length; i  )
{
let num = i   1; 
sum  = num;
}
alert(`The sum of all numbers from 1 to ${theNumber} is ${sum}`);
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>

  • Related