2

Only works with some numbers but is not working when i try to insert 3-10 for example. i don't know what is wrong. I'm still learning Javascript. Sorry for my bad english. Thank You

let btn = document.getElementById("btn")
let msg = document.getElementById("avvisi")

btn.addEventListener("click", () => {

  let primo = document.forms['modulo']['primonum'].value
  let secondo = document.forms['modulo']['secondonum'].value




  for (let i = primo; i <= secondo; i++) {

    console.log(i * i)
  }

})
<form id="modulo">
  inizio <input type="text" id="primonum"> fine <input type="text" id="secondonum">
  <input type="button" id="btn" value="go">
</form>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
Cecca86
  • 21
  • 1
  • For me it seems to work, where does it fail? – Aalexander Feb 14 '21 at 09:48
  • What exactly is your program supposed to do? It seems you say that you want to print the square root for each number between two numbers but you are just printing the squares of every number in between your two chosen numbers? – Da Mahdi03 Feb 14 '21 at 09:49
  • Yes, that is what i would like to do. But it seems that it works fine just with some numbers, if i try to put 3 as the start number and 10 as the final number it doesn't print anything. – Cecca86 Feb 14 '21 at 09:52
  • I would like to understand why if i put 1 and 10 it works fine but if i put 3 and 10 does not work at all, I’m sorry if I can’t explain myself better – Cecca86 Feb 14 '21 at 09:56

2 Answers2

3

You need to convert the strings from the input to a number. The shortest way is to use an unary plus + in front of the expression.

let btn = document.getElementById("btn");
let msg = document.getElementById("avvisi");

btn.addEventListener("click", () => {
    let primo = +document.forms['modulo']['primonum'].value
    let secondo = +document.forms['modulo']['secondonum'].value
    for (let i = primo; i <= secondo; i++) {
        console.log(i * i);
    }
});
<form id="modulo">
  inizio <input type="text" id="primonum"> fine <input type="text" id="secondonum">
  <input type="button" id="btn" value="go">
</form>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

primo and secondo are strings because they came from an input. So when you set i to primo i is also a string. When comparing "3" to "10", "3" is bigger than "10" because of their unicode values and it skips the loop because i <= secondo is false in this case. Doing i*i can only work with numbers so javascript turns them into numbers and it works. The solution would be to turn the strings into numbers directly.

let primo = Number(document.forms['modulo']['primonum'].value);
let secondo = Number(document.forms['modulo']['secondonum'].value);

or

let primo = +document.forms['modulo']['primonum'].value;
let secondo = +document.forms['modulo']['secondonum'].value;
lusc
  • 1,206
  • 1
  • 10
  • 19