Chris
Chris

Reputation: 21

Value returning 0 or NaN instead of actual result

Just trying to make a simple weight converter program, but the result keeps giving me NaN or 0. I have coded a similar calculator using basically the same function and it works fine, I'm not sure what I am missing here.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=1, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="weight.js"></script>
    <title>Weight Converter</title>
</head>
<body>

    <div>
        <input id="pounds" type="text" placeholder="Enter weight in pounds"/>
        <input type="button" value="convert" onclick="calc()"/>
    </div>




</body>
</html>

JS:

var k = document.getElementById('pounds').value;


function calc(){
    var result = (k / 2.2);
    alert(result + " kilograms");
    console.log(result);
}

Upvotes: 0

Views: 60

Answers (2)

Hunter Frazier
Hunter Frazier

Reputation: 477

Maybe try something like this. Wait for window to load then run calc function (which will already have the DOM available (e.g. any div ID's or classes) since Window.load has been invoked)

window.onload = function() {
  calc();
};

function calc() {
  let k = document.getElementById('pounds');
  k.addEventListener('click', function () {
    let result = document.getElementById('pounds').value / 2.2;
    alert(result.toFixed(1) + " kilograms");
    console.log(result);
  });
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

You're trying to get the .value before the onclick has been triggered. On page load, the value of the element is an empty string. Try getting the value after the click, not before:

function calc() {
  var k = document.getElementById('pounds').value;
  var result = (k / 2.2);
  alert(result + " kilograms");
  console.log(result);
}
<div>
  <input id="pounds" type="text" placeholder="Enter weight in pounds" />
  <input type="button" value="convert" onclick="calc()" />
</div>

Upvotes: 3

Related Questions