Javascript mathematics with decimal calculation - javascript

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>

Related

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);
});
});
});

Remove NaN from input while calculation

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>

My variable refused to display in my Div

The country is changing along side the shipping. I could alert my shipping but will refuse to display in my div. What could be wrong? All calculations working well and displays well except for the #usashipping please help. My country changes and give the correct value for the calculation. The shipping fee just will not display.
<!-- language: lang-js -->
<script type="application/javascript">
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
$('.add').click(function() {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput= currentValue + 1;
$('#gems').val(newinput);
(newinput);
if(newinput==1)
{
var np1=(19.99*2.0);
flpay= np1.toFixed(2);
$('#flpay').html(flpay);
var tot= (fees + shipping + flpay);
var total= tot.toFixed(2);
$('#total').html(total);
var newp=19.99;
var price= newp.toFixed(2);
$('#price').html(price);
useprice= 19.99;
}
else if(newinput>1)
{
//useprice=useprice;
var newprice= 19.99 + (9.99*(newinput-1));
var np1 =(2*newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot =( fees + shipping + (2*newprice) );
var total= tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp= newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
First & Last Months Payment = $<span data-first-last-month-fees="" id="flpay"></span>
</div>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
<div>
Total due today : $<span data-total-due="" id="total"></span>
</div>
Your code should work perfectly, but there are few things that you could improve in your code:
Instead of declaring shipping variable 3 times in each condition, you need to declare it only once, then update it in each condition, and make sure it's stored as a string so it can be displayed correctly in your HTML.
Instead of updating the HTML content of your span in every condition, just update it with the shipping amount in the end.
This is how should be your code:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
Demo:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="country">
<option value="40">40</option>
<option value="236">236</option>
<option value="100">100</option>
</select>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
I can see error showing in your code. I found "$('.add').click" inside "$('#country').change". Also "$('#country').change" function you declared local variable "var shipping;" that's why no change on global "shipping;" value but you using it inside "$('#country').change" function. I modified little bit now try with following code and comment reply if not work for you:
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
})
$('.add').click(function () {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput = currentValue + 1;
$('#gems').val(newinput);
(newinput);
if (newinput == 1) {
var np1 = (19.99 * 2.0);
flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + flpay);
var total = tot.toFixed(2);
$('#total').html(total);
var newp = 19.99;
var price = newp.toFixed(2);
$('#price').html(price);
useprice = 19.99;
}
else if (newinput > 1) {
//useprice=useprice;
var newprice = 19.99 + (9.99 * (newinput - 1));
var np1 = (2 * newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + (2 * newprice));
var total = tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp = newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
})
I only changed the div id from #usashipping to something else and it works just fine. Maybe #usashippingis now a constant in jquery library.

Open modal window after form calculations function is complete

Open modal window after form calculations function is complete
I have a basic form that has check boxes. Each checkbox is a different (simple) calculation. At the end of the function some more calculations are done and stored in variables.
I need to first run this calculation function from an onclick event and then display them in a modal window.
I am using Magnific-Pop up at the moment.
I know that the calculations have to be done first so the variables have the data. But I don’t know how to run the function and then pop up the window.
Now, when the button is clicked the window opens before the function is run.
Form button
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
The Modal window
$('.ajax-popup-link').magnificPopup({
items: {
src: '#popup',
type: 'inline',
//preloader: true,
},
});
This code displays a div with all the variables. The constant variables display but not the final calcs.
Here is the div
<div id="popup" class="white-popup mfp-hide">
<table class="data savings">
<thead>
<tr>
<th colspan="2"><script>document.write(VarFromCalc);</script></th>
</tr>
</thead>
<tbody>
<tr>
<td>Number of patients with potential Reduced Length of Stay</td>
<td class="stay" id="stay">$ <script>document.write(totalN);
</script> </td>
</tr>
</tbody>
</table>
If the modal window (of course) opens before the calculations are done the values are 0.
I hope this makes sense. If you need more info let me know.
Here is the calculation script.
<script>
var n3, n4, n5, n6, totalW, totalB, totalU, totalT, totalN;
var finalCalc;
var n7;
function calculate() {
if (document.getElementById('check1').checked) {
var check01 = 6 * 7.08;
var c01 = check01.toFixed(2);
}
else {var c01 = 0;}
if (document.getElementById('check2').checked) {
var check02 = 4 * 4.62;
var c02 = check02.toFixed(2);
}
else {var c02 = 0;}
if (document.getElementById('check3').checked) {
var check03 = 6 * 13.20;
var c03 = check03.toFixed(2);
}
else {var c03 = 0;}
if (document.getElementById('check4').checked) {
var check04 = 6 * 16.00;
var c04 = check04.toFixed(2);
}
else {var c04 = 0;}
if (document.getElementById('check5').checked) {
var check05 = 3 * 1.32;
var c05 = check05.toFixed(2);
}
else {var c05 = 0;}
if (document.getElementById('check6').checked) {
var check06 = 1 * 12.30;
var c06 = check06.toFixed(2);
}
else {var c06 = 0;}
if (document.getElementById('check7').checked) {
var check07 = 4 * 3.16;
var c07 = check07.toFixed(2);
}
else {var c07 = 0;}
if (document.getElementById('check8').checked) {
var check08 = 4 * 4.68;
var c08 = check08.toFixed(2);
}
else {var c08 = 0;}
if (document.getElementById('check9').checked) {
var check09 = 3 * 12.91;
var c09 = check09.toFixed(2);
}
else {var c09 = 0;}
if (document.getElementById('check10').checked) {
var check10 = 3 * 13.55;
var c10 = check10.toFixed(2);
}
else {var c10 = 0;}
if (document.getElementById('check11').checked) {
var check11 = 3 * 50.60;
var c11 = check11.toFixed(2);
}
else {var c11 = 0;}
if (document.getElementById('check12').checked) {
var check12 = 4 * 11.36;
var c12 = check12.toFixed(2);
}
else {var c12 = 0;}
if (document.getElementById('check13').checked) {
var check13 = 1 * 93.58;
var c13 = check13.toFixed(2);
}
else {var c13 = 0;}
if (document.getElementById('check14').checked) {
var check14 = 3 * 18.48;
var c14 = check14.toFixed(2);
}
else {var c14 = 0;}
if (document.getElementById('check15').checked) {
var check15 = 3 * 39.93;
var c15 = check15.toFixed(2);
}
else {var c15 = 0;}
if (document.getElementById('check16').checked) {
var check16 = 2 * 5.98;
var c16 = check16.toFixed(2);
}
else {var c16 = 0;}
if (document.getElementById('check17').checked) {
var check17 = 1 * 12.30;
var c17 = check17.toFixed(2);
}
else {var c17 = 0;}
if (document.getElementById('check18').checked) {
var check18 = 1 * 50.73;
var c18 = check18.toFixed(2);
}
else {var c18 = 0;}
if (document.getElementById('check19').checked) {
var check19 = 3 * 4.36;
var c19 = check19.toFixed(2);
}
else {var c19 = 0;}
if (document.getElementById('check20').checked) {
var check20 = 3 * 284.58;
var c20 = check20.toFixed(2);
}
else {var c20 = 0;}
if (document.getElementById('check21').checked) {
var check21 = 1 * 214.27;
var c21 = check21.toFixed(2);
}
else {var c21 = 0;}
if (document.getElementById('check22').checked) {
var check22 = 2 * 78.00;
var c22 = check22.toFixed(2);
}
else {var c22 = 0;}
if (document.getElementById('check23').checked) {
var check23 = 4 * 6.13;
var c23 = check23.toFixed(2);
}
else {var c23 = 0;}
if (document.getElementById('check24').checked) {
var check24 = 1 * 4.78;
var c24 = check24.toFixed(2);
}
else {var c24 = 0;}
if (document.getElementById('check25').checked) {
var check25 = 2 * 14.52;
var c25 = check25.toFixed(2);
}
else {var c25 = 0;}
if (document.getElementById('check26').checked) {
var check26 = 1 * 229.44;
var c26 = check26.toFixed(2);
}
else {var c26 = 0;}
if (document.getElementById('check27').checked) {
var check27 = 1 * 9.68;
var c27 = check27.toFixed(2);
}
else {var c27 = 0;}
var h51 = (parseFloat(c01) + parseFloat(c02) + parseFloat(c03) + parseFloat(c04) + parseFloat(c05) + parseFloat(c06) + parseFloat(c07) + parseFloat(c08) + parseFloat(c09) + parseFloat(c10) + parseFloat(c11) + parseFloat(c12) + parseFloat(c13) + parseFloat(c14) + parseFloat(c15) + parseFloat(c16) + parseFloat(c17) + parseFloat(c18) + parseFloat(c19) + parseFloat(c20) + parseFloat(c21) + parseFloat(c22) + parseFloat(c23) + parseFloat(c24) + parseFloat(c25) + parseFloat(c26) + parseFloat(c27));
//per month calcs
var j3 = parseFloat(100);
var j4 = parseFloat(200);
var j5 = parseFloat(250);
var j6 = parseFloat(200);
var j7 = parseFloat(600);
var k3 = parseFloat(j3) * 12;
var k4 = parseFloat(j4) * 12;
var k5 = parseFloat(j5) * 12;
var k6 = parseFloat(j6) * 12;
//var k7 = parseFloat(j7)*12;
var l3 = parseFloat(3573);
var l4 = parseFloat(2033);
var l5 = parseFloat(4706);
var l6 = parseFloat(3437);
var m3 = parseFloat(j3)*parseInt(l3);
var m4 = parseFloat(j4)*parseInt(l4);
var m5 = parseFloat(j5)*parseInt(l5);
var m6 = parseFloat(j6)*parseInt(l6);
n3 = Math.round(parseFloat(k3)*parseFloat(l3));
n4 = Math.round(parseFloat(k4)*parseFloat(l4));
n5 = Math.round(parseFloat(k5)*parseFloat(l5));
n6 = Math.round(parseFloat(m6) * 12);
n7 = Math.round(parseFloat(j7) * parseFloat(h51) * 12);
//STORE FINAL CALCS
totalW = n3.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalB = n4.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalU = n5.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalT = n6.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalN = n7.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var totalCalc = Math.round(parseFloat(n3) + parseFloat(n4) + parseFloat(n5) + parseFloat(n6) + parseFloat(n7));
finalCalc = totalCalc.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$('.ajax-popup-link').click();
}
</script>
Then i try to show the vars in the hidden div popup as such
<tr>
<td>Total ID/AST Cultures</td>
<td class="cultures" id="cultures">$ <script>document.write(totalT);</script></td>
</tr>
Google Charts Code
var data = google.visualization.arrayToDataTable([
['Element', 'Savings', { role: 'style' }],
['Reduced Length of Stay', n7, ''],
['Total ID/AST Cultures', n6, ''],
['Urine', n5, ''],
['Blood', n4, ''],
['Wound/Abscess', n3, '' ],
]);
I don't know much about magnificPopup, but in this case, you can actually just add a hidden div with "ajax-popup-link" class, and remove this class from the link.
in the Calculate() function, after everything is done, you call "$('.ajax-popup-link').click()" to bring up the modal.
To implement it, do like following:
change
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
to
<input type="button" class="calculate" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
To correctly set the calculated value to the popup window, you can add a id to the node that need to display the value, like following html code:
<th colspan="2" id="var_from_calc"></th>
And in the calculate() function, after you have finished calculating, add this code:
$('#var_from_calc').html(VarFromCalc);
$('#stay').html(totalN);
$('.ajax-popup-link').click()

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