Remove NaN from input while calculation - javascript

I have a javascript function in which I need to remove the NaN from textbox after calculation ?
function calculateInterest() {
var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
var no_of_months = parseInt(document.getElementById("repayment_periods").value);
var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
var no_of_periods = no_of_months / 12;
{
var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;
var pay_interest = payable_interest.toFixed(2);
document.getElementById("total_payable_interest").value = pay_interest;
var repay_amount = (loan_amount / no_of_months).toFixed(2);
document.getElementById("repayment_amount").value = repay_amount;
var total_payable_amount = (payable_interest + loan_amount).toFixed(2);
document.getElementById("total_payable_amount").value = total_payable_amount;
}
}

Use isNaN() function
Example:
var repay_amount = (loan_amount / no_of_months).toFixed(2);
if(!isNaN(repay_amount)) //if is NaN don't set value
document.getElementById("repayment_amount").value = repay_amount;

When assigning a value to a textbox, check if it is NaN or not:
if(!isNaN(parseInt(value_to_test)))
document.getElementById("yout_input").value = value_to_test;
else
document.getElementById("yout_input").value = '0'; // or anything you want to show here

you can change your code like below using isNaN() method of javascript
{
var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;
var pay_interest = payable_interest.toFixed(2);
document.getElementById("total_payable_interest").value = isNaN(pay_interest) ? 0 : pay_interest;
var repay_amount = (loan_amount / no_of_months).toFixed(2);
document.getElementById("repayment_amount").value = isNaN(repay_amount) ? 0 : repay_amount;
var total_payable_amount = (payable_interest + loan_amount).toFixed(2);
document.getElementById("total_payable_amount").value = isNaN(total_payable_amount) ? 0 : total_payable_amount;
}

Using isNan() will help you :
see below snippet :
function calculateInterest() {
var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value) ;
var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
var no_of_months = parseInt(document.getElementById("repayment_periods").value);
var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
var no_of_periods = no_of_months / 12;
{
var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;
var pay_interest = payable_interest.toFixed(2);
pay_interest = isNaN(pay_interest) ? 0 : pay_interest;
document.getElementById("total_payable_interest").value = pay_interest;
var repay_amount = (loan_amount / no_of_months).toFixed(2);
repay_amount = isNaN(repay_amount) ? 0 : repay_amount;
document.getElementById("repayment_amount").value = repay_amount;
var total_payable_amount = (payable_interest + loan_amount).toFixed(2);
total_payable_amount = isNaN(total_payable_amount) ? 0 : total_payable_amount;
document.getElementById("total_payable_amount").value = total_payable_amount;
}
}
emp_loan_repayment_method : <input id="emp_loan_repayment_method_id" value="100" />
<br>
maximum_loan_amount : <input id="maximum_loan_amount" value ="50" />
<br>
rate_of_interest : <input id="rate_of_interest" value="2" />
<br>
repayment_periods : <input id="repayment_periods" value="3" />
<br>
repayment_amount : <input id="repayment_amount" value="200" />
<br><br><br>
total_payable_interest : <input id="total_payable_interest" />
<br><br>
total_payable_amount : <input id="total_payable_amount" />
<br><br>
<button onclick="calculateInterest()" >Calculate</button>

Related

how to change input text value has been set in javascript

i want asking about javascript. i develop a tax calculation system.
function countsisa(){
var iv = document.getElementById("invoicevalue");
var ppn = document.getElementById("ppn");
var pph = document.getElementById("pph");
var dpp = document.getElementById("dpp");
var propv = document.getElementById("propertyvalue");
var shipv = document.getElementById("shippingvalue");
var dppship = document.getElementById("dppshipping");
var pph23 = document.getElementById("pph23");
var total = document.getElementById("total");
var income = document.getElementById("income");
var ppndoc = document.getElementById("ppndoc");
var pphdoc = document.getElementById("pphdoc");
var pphdoc23 = document.getElementById("pphdoc23");
if(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("propertyvalue").disabled = true;
document.getElementById("shippingvalue").disabled = true;
document.getElementById("dppshipping").disabled = true;
document.getElementById("pph23").disabled = true;
dpp.value = Math.ceil(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
ppn.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.10);
income.value = iv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-pph.value-ppn.value;
}else{
if(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("invoicevalue").disabled = true;
total = parseFloat(propv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10)+parseFloat(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10);
// total = String(total);
propv.value = String(propv.value);
shipv.value = String(shipv.value);
dpp.value = Math.ceil(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
dppship.value = Math.ceil(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
pph23.value = Math.ceil(dppship.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.02);
ppn.value = (propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") - dpp.value)+(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-dppship.value);
income.value = total-pph.value-ppn.value-pph23.value;
}else{
document.getElementById("propertyvalue").disabled = false;
document.getElementById("shippingvalue").disabled = false;
document.getElementById("dppshipping").disabled = false;
document.getElementById("pph23").disabled = false;
}
}
console.log(total);
if(dpp.value <= 0){
dpp.value = 0;
}
if(dppship.value <= 0){
dppship.value = 0;
}
if(pph.value <= 0){
pph.value = 0;
}
if(pph23.value <= 0){
pph23.value = 0;
}
if(ppn.value <= 0){
ppn.value = 0;
}
if(income.value <= 0){
income.value = 0;
}
dppship.value = tandaPemisahTitik(dppship.value);
dpp.value = tandaPemisahTitik(dpp.value);
pph.value = tandaPemisahTitik(pph.value);
pph23.value = tandaPemisahTitik(pph23.value);
ppn.value = tandaPemisahTitik(ppn.value);
pphdoc.value = tandaPemisahTitik(pph.value.replace(/[.*+?^${}()|[\]\\]/g,""));
pphdoc23.value = tandaPemisahTitik(pph23.value.replace(/[.*+?^${}()|[\]\\]/g,""));
ppndoc.value = tandaPemisahTitik(ppn.value);
income.value = tandaPemisahTitik(income.value);
}
this my javascript code to count value and display it in input value.
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="ppn"><?php print _('mi_invoice_ppn'); ?></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon" style="border-radius:0px;">Rp</span>
<input type="text" name="ppn" id="ppn" class="form-control" onkeydown="return numbersonly(this, event);" onkeyup="javascript:tandaPemisahTitik(this);" placeholder="0" />
</div>
</div>
</div>
this is the input code. i want change input text value has been count in javascript function. i want to manually changed again. so javascript function to count automatic. and can edit again if miscalculation.
If you want to recalculate when any input value's changed, you can add change listener on the input elements.
will be look like:
let inputElems = document.querySelectorAll("input");
for (let i = 0, len = inputElems.length; i < len; i++) {
inputElems[i].addEventListener("change", countsisa);
}

Why is my form outputting NaN?

So I have this form that is performing very basic calculations and when I submit it, it results to NaN.
The thing that is confusing me is when I do a typeof of one of the variables assigned to the value of each input, it returns "number", and yet I get NaN as a result. Can anyone tell me why or what it is I am doing wrong?
Here's my HTML:
<form name="baddiesCost">
<input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
<input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
<input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
<button id="submitForm">Submit</button>
</form>
<h1 id="total"></h1>
Here's my JavaScript:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
This statement document.baddiesCost.bobombs.value * bobombsCost; uses variable bobombsCost which is not defined at this time.
So, it is similar to: document.baddiesCost.bobombs.value * undefined; which will be NaN.
To solve this put variable inicialization before usage like in following code:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
Anyway, NaN is number type, you can refer to following post for more explaination.

On mouse hover, display the corresponding sizes of bars, as mentioned in the input field

function draw() {
var nums = document.getElementById("number").value.split(",");
console.log(nums);
var w = 40;
var factor = 20;
var n_max = Math.max.apply(parseInt, nums);
var h_max = factor * n_max;
console.log("h max is " + h_max);
console.log("n max is " + n_max);
//var h_max = Math.max(h);
//var a = parseInt(nums);
//var create = document.getElementById("shape");
for (var i = 0; i <= nums.length; i++) {
//var x = parseInt(nums[i]);
//var final_width = w / x;
var x_cor = (i + 1) * w;
//var y_cor = i * w * 0.5;
var h = factor * nums[i];
console.log(x_cor);
console.log(h);
//console.log(h_max);
var change = document.getElementById("histContainer");
//change.className = 'myClass';
var bar = document.createElement("div");
bar.className = 'myClass';
//var c_change = document.createElement("div2");
//change.appendChild(c_change);
change.appendChild(bar);
console.log(change);
//change.style.x.value = x_cor;
//change.style.y.value = y_cor;
bar.style.position = "absolute";
bar.style.top = (h_max - h) + "px";
//bar.style.transform = "rotate(-1deg)"
bar.style.left = i * w * 1 + "px";
bar.style.backgroundColor = "rgb(1,211,97)";
bar.style.opacity = "0.6";
bar.style.width = w + "px";
bar.style.height = h + "px";
//var color1 = document.getElementById("histContainer");
//var bar_color = document.createElement("div");
//color1.appendChild(change);
//bar.style.color = "rgba(1,211,97,0.6)";
}
}
function color() {
//draw();
var change1 = document.getElementsByClassName('myClass');
for (var i = 0; i < change1.length; i++) {
change1[i].style.backgroundColor = "rgb(255,0,27)";
console.log("Change1 = " + change1[i]);
}
// var bar1 = document.createElement("div2");
// change1.appendChild(bar1);
// console.log(change1);
//change1.style.backgroundColor = "rgb(1,,254,16)";
}
$(document).ready(function() {
$(document).on("mouseover", ".myClass", function() {
//var number = this.nums;
//$(this.nums).text($(this.nums).index());
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout", ".myClass", function() {
$(this).css("opacity", shade);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Number:<input type="text" id="number" /><br>
<input type="button" id="button1" value="Draw" onClick="draw()" /><br>
<input type="button" id="button2" value="Change Color" onClick="color()" /><br>
<div id="histContainer" style="position: relative;"> </div>
<!-- <label for="mouseover" id="label1">Bar Value</label><br>
<input type="text" name="mouseover" id="text2" value="0"/><br> -->
<!-- <input type="button" id="color_change" style="float: right;" value="Change Color" /> -->
My Question is- I have entered some numbers as Input, and corresponding histogram is made according to the input values. Now, I have created mouseover() on each bar, and WANT to display their proportionate sizes, as given in input.
Can you provide me some help? Only thing which i figured out was- I have to call my draw function in the jQuery mouseover.
REFER TO the draw() and jQuery function(last)
I have figured out the answer. It is required that the nums array has to be re-declared again.
Solution Achieved
$(document).ready(function() {
$(document).on("mouseover",".myClass", function(){
//var numbers = $("#number").serialize();
//var number = this.nums;
var nums = document.getElementById("number").value.split(",");
$(this).text(nums[$(this).index()]);
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout",".myClass", function() {
$(this).css("opacity", shade);
});
});
});

Javascript mathematics with decimal calculation

I have a weird problem with javascript mathematics here is my code :
<script>
function four() {
var price = document.getElementById("price").value;
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
</script>
and when the price is 100 ( price = 100 )
pish : 334.1666666666667
ghest : 167.08333333333331
how can i fix that ?
Here's a solution you had to parse the value that you get from your element.
function four() {
var priceUnparsed = document.getElementById("price").value;
var price= parseFloat(priceUnparsed );
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
alert(pishpardakht);
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
<input id="price" value="100">
<button onclick="four()">Go</button>

How to get value from input field using javascript

I have some problem to get value from input field. Some input field is a result from calculation process, such as #t1_potensi and #t2_potensi. While #aliran is the result of the overall calculation process.
This is my HTML code.
<input oninput="hitung()" name="v_potensi" id="v_potensi" type="text" placeholder="liter . . ." />
<input oninput="hitung()" name="a_potensi" id="a_potensi" type="text" placeholder="menit . . ." />
<input oninput="hitung()" name="b_potensi" id="b_potensi" type="text" placeholder="menit . . ." />
<input oninput="hitungT1()" name="kecepatan_air" id="kecepatan_air" type="text" placeholder="km/jam . . ." />
<input oninput="hitungT1()" name="jarak1" id="jarak1" type="text" placeholder="kilometer . . ." />
<input oninput="hitungT2()" name="kecepatan_back" id="kecepatan_back" type="text" placeholder="km/jam . . ." />
<input oninput="hitungT2()" name="jarak2" id="jarak2" type="text" placeholder="kilometer . . ." />
<!-- #t1_potensi = 0.65 + ((60 / #kecepatan_air) * #jarak1) -->
<input readonly="readonly" oninput="hitung()" name="t1_potensi" id="t1_potensi" type="text" placeholder="menit . . ." />
<!-- #t2_potensi = 0.65 + ((60 / #kecepatan_back) * #jarak2) -->
<input readonly="readonly" oninput="hitung()" name="t2_potensi" id="t2_potensi" type="text" placeholder="menit . . ." />
<!-- #aliran = (#v_potensi / (#a_potensi + #b_potensi + #t1_potensi + #t2_potensi)) - 0.1 -->
<input readonly="readonly" name="aliran" id="aliran" type="text" placeholder="liter/menit . . ." />
I use javascript to do the calculation process, to get a result for #t1_potensi and #t2_potensi. My problem start when i try to calculate overall (#aliran), my javascript function in particular to obtain the overall result can not work properly. Here my javascript for #t1_potensi, #t2_potensi, and #aliran.
//To get #t1_potensi
function hitungT1() {
var kecKm = document.getElementById('kecepatan_air').value;
var d1 = document.getElementById('jarak1').value;
var result = document.getElementById('t1_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d1 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #t2_potensi
function hitungT2() {
var kecKm = document.getElementById('kecepatan_back').value;
var d2 = document.getElementById('jarak2').value;
var result = document.getElementById('t2_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d2 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #aliran
function hitung() {
var vol = document.getElementById('v_potensi').value;
var a = document.getElementById('a_potensi').value;
var b = document.getElementById('b_potensi').value;
var t1 = document.getElementById('t1_potensi').value;
var t2 = document.getElementById('t2_potensi').value;
var hasil = document.getElementById('aliran');
//convert liter to galon
var galon = Math.round(vol * 0.264172051);
var sumT = t1 + t2;
var sum = a + sumT + b;
var dev = galon / sum;
var result = Math.round(dev - 0.1);
hasil.value = result;
}
Does anyone can help me to solve my problem? or maybe make my javascript function more efficient. thanks.
Use parseFloat() on the numbers you're getting with document.getElementById('...').value:
//To get #t1_potensi
function hitungT1() {
var kecKm = parseFloat(document.getElementById('kecepatan_air').value);
var d1 = parseFloat(document.getElementById('jarak1').value);
var result = document.getElementById('t1_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d1 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #t2_potensi
function hitungT2() {
var kecKm = parseFloat(document.getElementById('kecepatan_back').value);
var d2 = parseFloat(document.getElementById('jarak2').value);
var result = document.getElementById('t2_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d2 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #aliran
function hitung() {
var vol = parseFloat(document.getElementById('v_potensi').value);
var a = parseFloat(document.getElementById('a_potensi').value);
var b = parseFloat(document.getElementById('b_potensi').value);
var t1 = parseFloat(document.getElementById('t1_potensi').value);
var t2 = parseFloat(document.getElementById('t2_potensi').value);
var hasil = document.getElementById('aliran');
//convert liter to galon
var galon = Math.round(vol * 0.264172051);
var sumT = t1 + t2;
var sum = a + sumT + b;
var dev = galon / sum;
var result = Math.round(dev - 0.1);
hasil.value = result;
}
Also, it's a bit tricky to me why you call the hitung() function only after editing one of the first three text boxes. Why not call all three functions every time any field is changed? Wouldn't that be better?
Up to you. Also, after you've placed parseFloat calls like above, please use console.log(string or variable to log), e.g. console.log('dev is: ' + dev). That way you can easily debug your code - see what all the values are during any calculation.
Also, do you really need to round the final result?

Categories