0

I have a form created in html, with two input fields and one button. When clicking on the button i want a function to be called for that will then add the two numbers and then display the sum via the alert function.

I know how to call for the function when the button is clicked, and i know how to read and store the two inputs in separate variables.

I would like some tips on how to in the easiest way validate the input as numbers only?

function Calculate() {
  var num1 = document.getElementById("num1").value;

  var num2 = document.getElementById("num2").value;
  num1_parsed = parseInt(num1);    

  num2_parsed = parseInt(num2);

  if (num1_parsed) {    

  } else {
    alert("Wrong input!!!");
    return false;    
  }

  var total = num1_parsed + num2_parsed;
  alert("The total sum of your numbers are: " + sum);
}

This code works for some reason, tho if num1 is correct but num2 is not it gives message NaN instead of the alert message!

charlietfl
  • 170,828
  • 13
  • 121
  • 150

6 Answers6

1

JavaScript Method

With JavaScript doing the validation, you can use the isNaN() function. This will return true if the input is not a number.

function Calculate() 
{
  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;

  num1_parsed = parseFloat(num1);    
  num2_parsed = parseFloat(num2);

  if(isNaN(num1_parsed) || isNaN(num2_parsed))
  {
      alert("Wrong input!!!");
      return false;
  } else {
      var total= num1_parsed + num2_parsed;
      alert("The total sum of your numbers are: " + total);
      return true;
  }
}

HTML5 Method

Additionally, if you wish to use HTML5 only to ensure the input values are number's then you can use the type="number" attribute to the input tag. This adds built-in validation to reject non-numerical numbers.

<input type="number" id="num1" />
<input type="number" id="num2" />
0

If you can use an input element as type="number"

num1_parsed = Number(num1);
num2_parsed = Number(num2);

if (isNaN(num1_parsed) || isNaN(num2_parsed) ) {
    alert("Wrong input!!!");
    return false;
} else {
    // do stuff
    return true;        
}
Ele
  • 33,468
  • 7
  • 37
  • 75
0

HTML

<input type="number" id="num1" />
<input type="number" id="num2" />
<button onClick="Calculate()" type="button">Get Sum</button>

JS

function Calculate() {
  var num1 = document.getElementById("num1").value;

  var num2 = document.getElementById("num2").value;
  num1_parsed = parseFloat(num1);    

  num2_parsed = parseFloat(num2);

  if (isNaN(num1_parsed) || isNaN(num2_parsed) ) {    
     alert("Wrong input!!!");
     return false;    
  }

  var total = num1_parsed + num2_parsed;
  alert("The total sum of your numbers are: " + total);
}

OR

function Calculate() {
  var num1 = document.getElementById("num1").value;

  var num2 = document.getElementById("num2").value;
  if( !num1 || !num2 ){
     alert("please enter values for num1 and num2");
  } 
  var total = eval(`${num1}+${num2}`);
  if( isNaN(total) ){
     alert("Wrong input!!!");
     return false;    
  }
  alert("The total sum of your numbers are: " + total);
}
Vinesh Goyal
  • 607
  • 5
  • 8
0

Using isNaN() function. It might be more readable to use || instead of && which would mean that the result would be false.

function Calculate() {

  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;
  
  num1_parsed = parseInt(num1);    
  num2_parsed = parseInt(num2);
  
  
 //console.log((!(isNaN(num1_parsed))).toString() + " " + num1_parsed);
 //console.log((!(isNaN(num2_parsed))).toString() +  " " + num2_parsed);

  if (!(isNaN(num1_parsed)) && !(isNaN(num2_parsed))){
  var total = num1_parsed + num2_parsed;
  alert("The total sum of your numbers are: " + total);
  
  } else {
alert("Wrong input!!!");
    return false;        
  }


}
<input id="num1" />
<input id="num2" />
<button onclick="Calculate()">Calculate</button>
jeffld
  • 726
  • 1
  • 9
  • 17
0

Solution:

You can use map combined with Number to perform the initial transform. Afterwards using reduce can give you the total. Then you simply check if any of the numbers equal NaN.


Code:

  let num = (n) => document.getElementById("num" + n).value,
    total = (numbers = [num(1), num(2)].map(Number)).reduce((a, v) => a + v);

  if (numbers.some(Number.isNaN)) alert("wrong");
  else alert("The total sum of your numbers are: " + total);

Note: It's important to realize that isNaN and Number.isNaN are different and will sometimes give different results. Number.isNaN specifically looks to see if a value is a number and if that number type is NaN. isNaN will coerce the supplied value. A.e. isNaN(undefined) and Number.isNaN(undefined) return true and false respectively.


Demo:

function Calculate() {
  let num = (n) => document.getElementById("num" + n).value,
    total = (numbers = [num(1), num(2)].map(Number)).reduce((a, v) => a + v);

  if (numbers.some(Number.isNaN)) alert("wrong");
  else alert("The total sum of your numbers are: " + total);


}

document.querySelector("button").addEventListener("click", Calculate);
<input id="num1" value="34" />
<input id="num2" value="100" />
<hr/>
<button>Calculate</button>
zfrisch
  • 8,474
  • 1
  • 22
  • 34
-2

Take input of two numbers from the user. Store it in a variable & print the sum and product of the two numbers.

  • 1
    This is a question that looks more like an academic work than a technical one. We’d love to help you. To improve your chances of getting an answer, here are some tips: https://stackoverflow.com/help/how-to-ask – Everson Rafael Jun 10 '21 at 18:24