JMay
JMay

Reputation: 361

How to get the value of an input[type="number"]

<select id="height" name="" id="">
   <option value="FEET">FEET</option>
   <option value="INCHES">INCHES</option>
</select>
    <input id="heightNum" type="number">

When I click btn, I want the number inside heightNum to display. However I either get a blank line in the console or "0". So if I type say 123 in the input, I still get "0" or a blank line. Thanks in advance.

var height = document.getElementById('height').value.toLowerCase();
var heightNum =  document.getElementById('heightNum').value;

function calcBmi () {
if (height=="feet") {
console.log(heightNum);
 }
}

btn.addEventListener('click', calcBmi);

Upvotes: 1

Views: 37

Answers (1)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

You're getting confused about when values are assigned to variables.

heightNum is a variable that gets initialized ONCE when the page first loads. This value will not automatically update as the heightNum element changes.

Simply fetch the control values inside calcBmi. Then you know you will be fetching the values as they are when the click event fires.

function calcBmi () {
    var height = document.getElementById('height').value.toLowerCase();
    var heightNum =  document.getElementById('heightNum').value;
    if (height=="feet") {
        console.log(heightNum);
     }
   }

btn.addEventListener('click', calcBmi);

Upvotes: 3

Related Questions