html - Javascript calculation returns NaN, when only first 2 sum inserted -
function kanded_arvutus() { var deebet1 = document.getelementbyid("deebet1").value; var kreedit1 = document.getelementbyid("kreedit1").value; var deebet2 = document.getelementbyid("deebet2").value; var kreedit2 = document.getelementbyid("kreedit2").value; var kokku_deebet = parsefloat(deebet1)+parsefloat(deebet2); document.getelementbyid("kokku_deebet").value = kokku_deebet.tofixed(2); var kokku_kreedit = parsefloat(kreedit1)+parsefloat(kreedit2); document.getelementbyid("kokku_kreedit").value = kokku_kreedit.tofixed(2); }
and html
<input onclick="kanded_arvutus();" onchange="kanded_arvutus();" type="text" class="form-control" name="deebet'.$i.'" id="deebet'.$i.'" placeholder="0" value=""> <input value="" onclick="kanded_arvutus();" onchange="kanded_arvutus();" type="text" class="form-control" name="kreedit'.$i.'" id="kreedit'.$i.'" placeholder="0"> <input type="text" class="form-control field" name="kokku_deebet" value="" id="kokku_deebet" placeholder="0"> <input type="text" class="form-control field" name="kokku_kreedit" value="" placeholder="0" id="kokku_kreedit">
and if insert kreedit1 , deebet1 values, jquery returns nan , if insert deebet2 , kreedit2 also, working.
someone maybe see, wrong here ?
thanks in advance, aimar.
please check variables not null or notdefined below, before addition,
if (typeof(deebet1) != 'undefined' && deebet1 != null && typeof(deebet2) != 'undefined' && deebet2 != null) { var kokku_deebet = parsefloat(deebet1)+parsefloat(deebet2); document.getelementbyid("kokku_deebet").value = kokku_deebet.tofixed(2); } if (typeof(kreedit1) != 'undefined' && kreedit1 != null && typeof(kreedit2) != 'undefined' && deebet2 != null) { var kokku_deebet = parsefloat(kreedit1)+parsefloat(kreedit2); document.getelementbyid("kokku_kreedit").value = kokku_deebet.tofixed(2); }
as john suggested can use following, check whether variables has real values.
if (deebet1 && deebet2) { var kokku_deebet = parsefloat(deebet1)+parsefloat(deebet2); document.getelementbyid("kokku_deebet").value = kokku_deebet.tofixed(2); } if (kreedit1 && kreedit2) { var kokku_deebet = parsefloat(kreedit1)+parsefloat(kreedit2); document.getelementbyid("kokku_kreedit").value = kokku_deebet.tofixed(2); }
Comments
Post a Comment