user8573900
user8573900

Reputation:

How to remove NaN on my calculation

I have some problem from my calculation

<select name="ifin" id="ifin" class="form-control input-lg" required >
    <option selected disabled >Select Finishing</option>
    <option value="hpl">HPL</option>
    <option value="cat">Cat Duco</option>    
</select>

 <input class="form-control" type="number" placeholder="Panjang" min="1" id="ipanjang" name="pan" >
 <input class="form-control" type="number" placeholder="Tinggi" min="1" id="itinggi" name="ting">

the result would be NaN if I did not fill the ipanjang and itinggi

var e = (document.getElementById("ifin").value);
var panjang = parseFloat (document.getElementById("ipanjang").value);
var tinggi = parseFloat (document.getElementById("itinggi").value);
var ht = 2.0;
var hf = 0.0;
var total = 0.0;

if (e == "hpl") {
    hf = 0.0;
}
else if (e == "cat") {
    hf = 0.5;
}
else {
    hf = 0.0;
}
total = panjang * tinggi * ht + hf;

Can I remove it or giving a hint that they should fill the input?

I can not use the required attribute because I do not use the submit button.

Upvotes: 0

Views: 84

Answers (1)

Văn Quyết
Văn Quyết

Reputation: 2526

var panjang = parseFloat(document.getElementById("ipanjang").value) || 0;
var tinggi = parseFloat(document.getElementById("itinggi").value) || 0;

parseFloat don't always return a number, it can return number, Infinity or NaN. (Reference)

|| operator in JavaScript:

  • var a = b || c; equals to: var a = b ? b : c
  • var a = (b || c), a will be true or false

Upvotes: 2

Related Questions