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;
}
}
3
  • possible duplicate of How to check whether a value is a number in javascript or jquery Commented May 24, 2015 at 20:19
  • It is working for me, see this JSFiddle. 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. Commented May 24, 2015 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. Commented May 24, 2015 at 20:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks turnloose, I got my answer from that link. I added parseint to var getal1 = parseInt(document.getElementById('getal1').value);
no problem! woohoo! first answer I've posted on stackoverflow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.