I am working on a script to calculate some stuff using multiple input. I have been copy-pasting my script because it has been working for 2 values calculations. For example:
//Diameter Pitch
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.dpModule').val());
var valZ = parseInt($('.dpJumlahGigi').val());
var sum = valZ*valM;
$("input#resultDP").val(sum);
});
});
But now I am trying to add another variable Phi (3.14) but the calculation is not working
//Circular Pitch
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valD = parseInt($('.cpPitchDiameter').val());
var valT = parseInt($('.cpAot').val());
var phi = parseInt($('3.14').val());
var sum = phi*valD/valT;
$("input#resultCP").val(sum);
});
});
The circular pitch script resulted with NaN, can anyone please fix my code? I am trying to make the following formula:
var sum = 3.14*valD/valT;
Much thanks in advance
Replace: var phi = parseInt($('3.14').val()); with var phi = 3.14;.
Your current code is trying to look for a '3.14'tag in your HTML so it returns "not a number" since that doesn't exist in the HTML.
Related
I'm a complete beginner trying to build a solar power calculator (why did I do this to myself) I've tried everything but I'm still stuck. The idea is that users use a range slider to add their monthly electricity bill to a calculator. I want to then use what they entered in a calculation to convert their monthly bill to kwh but Console log shows "undefined" I have some constants that works with the value entered by the user. The calculation works if used without user input for the monthly electricity bill - a constant (I tested it) but I can't figure out how to use the user input in the calculation. Here's a codepen of what I did. The function I got there is probably a total mess but I don't know how to fix it. Please help, my brain have turned to mush and this is due tomorrow. I started like a month ago on this having to restart all the time because there is so much that needs to go in here and I don't know what I'm doing.
<h2>Solar Power Calculator</h2>
Monthly Electricity Bill:
<input type="range" min="100" max="10000" value="0" step="1" onchange="getSliderValues(this.value)" style="width:400px;">
<span id="monthlyBillval">0%</span>
<h2>Monthly Bill to KWH <span id="monthlyBill"></span></h2>
//initial variables
var phases = 1;
var systemCost = 247765.00;
var sizeOfPanelArray = 8.19;
var batteryBankCapacity = 22.20;
var payBackPeriod = 5.3;
var monthlyEstimatedSavings = 3864.00
// var amortData = [];
// Constants
var singlePhaseBaseCost = 41000;
var threePhaseBaseCost = 69000;
var panelCost = 2639;
var fiveKwSinglePhaseInverter = 17371;
var eightKwSinglePhaseInverter = 28344;
var twelveKwThreePhaseInverter = 43783;
var batteryCost = 29160;
var panelPeakPower = 455;
var avgDailySunHrs = 5.33;
var avgDaysPerMonth = 30.5;
var batteryCapacity = 7.4;
var maxCeilingDiscountedBracketInRands = 1440;
var lowBracketKwh = 600;
var discountedTarrif = 2.400395;
var higherTarrif = 3.312575;
function getSliderValues (billSlider){
var monthlyBill = document.getElementById('monthlyBill');
var monthlyBillval = document.getElementById('monthlyBillval');
monthlyBillval.innerHTML = billSlider;}
var monthlyBillToKwhConversion;
if (monthlyBillval < maxCeilingDiscountedBracketInRands) {
monthlyBillToKwhConversion = monthlyBillval / higherTarrif
}
else if (monthlyBillval > maxCeilingDiscountedBracketInRands) {
monthlyBillToKwhConversion = Math.round (((monthlyBillval - maxCeilingDiscountedBracketInRands)/ higherTarrif) + (maxCeilingDiscountedBracketInRands/discountedTarrif))
}
console.log("monthly bill to kWh conversion:" + monthlyBillToKwhConversion);
You're trying to access the monthlyBillval variable from outside the scope of the function where it's defined. That's not possible in Javascript as each variable is accessible only inside the scope of the function that defined it.
So all your if checks yield false, hence monthlyBillToKwhConversion remains undefined
Consider to return something from your function if you need outside it.
Moreover, in modern Javascript it's considered a best practice to avoid the var declaration because could lead to unexpected results and mess up the global scope. You should use let and const to define your variables.
Your code has some scope issues, also :
var monthlyBillval = document.getElementById('monthlyBillval');
monthlyBillval is an element not value, you can't do this:
monthlyBillToKwhConversion = monthlyBillval / higherTarrif
you can see the working code on codeopen
I've coded a small compound interest calculator. The last output-field has to show the amount calculated with the inputs above. But it should be rounded to two decimals and I didn't get it to work with various code-snippets I found on the web and even stackoverflow.
var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput
$button9.click(function(){
$counter5.val( parseInt($counter1.val()) * ((parseInt($counter4.val()) / 100) + 1) ** parseInt($counter3.val() ) ); // Calculates amount and loads it into .counter5
Useful ideas would be highly appreciated, thanks.
Have you tried using Number.toFixed yet?
var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput
$button9.click(function(){
$counter5.val(
( // begin calculation
parseInt($counter1.val()) *
((parseInt($counter4.val()) / 100) + 1) **
parseInt($counter3.val() )
) // end calculation
.toFixed(2) // round it to two decimals
); // pass it to counter5
});
I am trying to calculate an angle in js using math js. I am experienced that when the division is between negative numbers js give me bad results. e.g. -6/-3 give me 20093 instead of 2.
How can I solve this? here below you can see a portion of console.log.
Here is the code:
var num = math.eval(parseInt(p[1]) - parseInt(d3.event.y));
var den = math.eval(parseInt(p[0]) - parseInt(d3.event.x));
if (den==0){
var angle = 0;
}else{
var m = math.eval(num/den);
if(m<1){
theta = m*100;
}else{
theta = m*100;
}
}
Syntax in code is num/den as you can see.
Thanks in advance
You can simply do -6/-3.
Run this in your developer tools console: alert(-6/-3); and you will see.
I think math.eval() expects a string like "-6/-3".
I am developing a simple application form where I am calculating experiences from maximum three employers. Now I want to add them up . The experiences are in the form of X years Y months and Z days. I have written following javascript function --
function total(){
var td;
var fd=parseInt(document.getElementById("LoS_days1").value);
var sd=parseInt(document.getElementById("LoS_days2").value);
var ld=parseInt(document.getElementById("LoS_days3").value);
var tm;
var fm=parseInt(document.getElementById("LoS_months1").value);
var sm=parseInt(document.getElementById("LoS_months2").value);
var lm=parseInt(document.getElementById("LoS_months3").value);
var ty;
var fy=parseInt(document.getElementById("LoS_year1").value);
var sy=parseInt(document.getElementById("LoS_year2").value);
var ly=parseInt(document.getElementById("LoS_year3").value);
td = (fd +sd +ld);
var rd = td%30;
var cm = Math.floor(td/30);
document.getElementById("Totalexp_day").value=rd;
tm = (cm + fm +sm +lm);
var rm = tm%12;
var cy = Math.floor(ty/12);
document.getElementById("Totalexp_month").value=rm;
ty = (cy + fy +sy +ly);
document.getElementById("Totalexp_year").value=ty;
}
I am getting a NaN message in each of the Totalexp_day, Totalexp_month and Totalexp_day field. Earlier I had some modified code that was not showing NaN message but it was not showing the desired results. Kindly suggest what to do to eliminate these two errors.
parseInt(document.getElementById("LoS_days1").value)
if the first character of the string cannot be converted to a number, parseInt will return NaN.
To avoid this, you can so something like is suggested here:
parseInt(document.getElementById("LoS_days1").value) || 0
If document.getElementById("Totalexp_day").value is empty then also it will return NaN. Make sure you have some number there.
Second alternative is reading document.getElementById("Totalexp_day").innerHTML and then applying parseInt
Probably you alert or console log the document.getElementById("Totalexp_day").value you would be more clearer why this problem is comming
I'm trying to create a script that get some values from several selectboxes and then do some math with them.
The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.
The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.
I've created a fiddle here I think that describes my problem best!
My script
function update_amounts() {
var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
var korting = ((100-perc)/100);
var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
var adviesprijsValue = parseFloat(adviesprijs) || 0;
var sum = 0.0;
$('#product_configure_form .product-configure-custom-option select').each(function () {
var optionText = $(this).find('option:selected').text();
var matches = optionText.match(/\(([^)]+)\)/g) || [];
if (matches.length > 0) {
var priceText = matches[matches.length - 1];
if (priceText.indexOf("€") > -1) {
var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
var priceValue = parseFloat(priceClean) || 0;
sum += priceValue;
}
}
});
var sum2 = sum+adviesprijsValue;
var sumBtw = (sum2*1.21).toFixed(2);
$('#amount').text('€' +sum2);//
$('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
}
$(document).ready(function(){
$( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
});
The HTML is pretty long so best is to take a look at the Fiddle.
Can anybody help me to make a correct calculation...?!
Thx in advance
Your conversion from Dutch formatting to normal float formatting is incorrect.
Consider using:
.replace(/[^\d,]/g,"").replace(",",".")
Working example: http://jsfiddle.net/pgaphma3/3/
EDIT
To allow also a plus or minus sign use /[^\d,\-+]/g