Home > Software engineering >  Calculation via html and Javascript
Calculation via html and Javascript

Time:04-15

I’m getting “NaN” as my “result”. I don’t want an answer unless I’m completely missing something, which may be the case. But if I’m just getting the syntax wrong just wave in a general direction of my error and maybe a little hint. I’d like to challenge myself to get this on my own as much as possible.

var splitAmounts = document.getElementById('locations').value;
var btuRating = document.getElementById('btuRating').value;

function calc() {
  document.getElementById('result').value = btuRating / splitAmounts;
}
<input type="text" Placeholder="Enter BTU Rating" id="btuRating" />
<select id='locations'>
  <option value='4000'>Directly Outside</option>
  <option value='5000'>Indoors</option>
  <option value=''>Through Vent</option>
  <option value=''></option>
</select>
<input type="text" placeholder="result" id="result" />
<button onclick="calc();">=</button>

CodePudding user response:

The key to your problem is that assigning the value of an element reference to a variable sets the value of that variable until you assign a new value to it.

Changing the value of an element will have no consequence for any variable already assigned a previous (possibly empty) value.

As you stated you wanted to figure it out for yourself, I would suggest you think about what your existing code is doing when the page first loads and what it tries to do later when the function is called from page button.

CodePudding user response:

set type to your input
Not a number => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

CodePudding user response:

Have you tried using parseFloat? Forms sometimes input data as strings.

  • Related