1

I am trying to make some kind of small calculator from scratch. I have a form with 2 input fields and a submit button. When the submit button is pressed, this function is executed. However, I am trying to check whether the values that the user puts in the fields is a number or not. I found the IsNaN function for this, but its not showing the alert it should give when the field has no number as value or when the field is left empty. This is my javascript function right now:

function rekenmachine(){
//Pak de ingevulde getallen
var getal1 = document.getElementById('getal1').value;
var getal2 = document.getElementById('getal2').value;


if(isNaN(getal1)){
    alert("Vul a.u.b. in beide velden een getal in.");  
}
else{
    var uitkomst = parseFloat(getal1) + parseFloat(getal2);
    document.getElementById('uitkomst').value = uitkomst;
}
}
Arjenovic
  • 302
  • 3
  • 15
  • possible duplicate of [How to check whether a value is a number in javascript or jquery](http://stackoverflow.com/questions/6449611/how-to-check-whether-a-value-is-a-number-in-javascript-or-jquery) – Scott May 24 '15 at 20:19
  • It is working for me, see [this JSFiddle](http://jsfiddle.net/0s5v8ebc/). To add, you are only checking for 'getal1' to be a number at the moment, if you fill in something that is not a number as 'getal2' you will not get an error. – B_s May 24 '15 at 20:24
  • @Bastiaan yes you are right however I would like it to work when the field is left empty too. Maybe I should ve been more clear about that. – Arjenovic May 24 '15 at 20:30

1 Answers1

3

I think this other stackoverflow post might help you out. Basically, there's some type conversion going on behind the scenes that doesn't behave as you might expect.

Community
  • 1
  • 1
turnloose
  • 101
  • 5