Home > Net >  can't get the output from javascript
can't get the output from javascript

Time:08-30

var weightkg=document.getElementById('weight').value;

    var heightinm=document.getElementById('height').value;
    
    function bmival (weightkg,heightinm){

        var hout=heightinm*2
        var output=weightkg/hout
        //make a full number
             // var r= Math.trunc(o)
             
         if (output<=18.5){
            return document.getElementById('print').innerHTML=`Your BMI is ${output} you are underweight` ;
         }
 
         else if(output>18.5 && o<25.5){
            return document.getElementById('print').innerHTML=`Your BMI is ${output} You come under fit catogery`;
         }
 
         else{
            return document.getElementById('print').innerHTML=`Your BMI is ${output} you are overweight and obese`;
         }
     }

[i am making a bmi cal that take input from user but i am getting a error and don't know what i am doing wrong]

** this is js code and when i run i get a NaN instead of Number **

CodePudding user response:

The values from an input field are strings so you must convert them into numbers


var heightinm =  document.getElementById('height').value; // one way to do it.

CodePudding user response:

The value you get from

var weightkg=document.getElementById('weight').value; 

seems to be a string instead of number. You need to convert values to do Math operations on them. NaN tells you output is not a number. Turn your values to number with parseInt method.

var weightkg = parseInt(document.getElementById('weight').value); 

or you can just put a " " to convert a string into number

var weightkg =  document.getElementById('weight').value; 

For Example.

const input = document.getElementById('input');
const defaultStringInput = document.getElementById('input').value;
const inputConverted = parseInt(document.getElementById('input').value);
const inputConverted2 =  document.getElementById('input').value;
input.addEventListener('change', () => {

  console.log(typeof defaultStringInput); // string
  console.log(typeof inputConverted); // number
  console.log(typeof inputConverted2); // number
});
  • Related