How do I make this conversion function work in both directions? - javascript
I'm new in JS and I have trouble to finish a converter only with inputs, I explain the problem !
We have two input, Meters and Feet. when I transmit a number to Feet I have the result in Meters. And I Want to do the same think with Meters . and vice versa
let metresEl = document.getElementById('inputMetres');
function LengthConverter(valNum) {
metresEl.value = valNum/3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres">
</div>
</div>
You can add another parameter in the LengthConvertor function which will say the input unit (meter or feet) and convert it accordingly inside the function using if.
function LengthConverter(valNum, inputUnit) {
if(inputUnit === 'feet')
metresEl.value = valNum/3.2808;
if(inputUnit === 'meter')
feetsEL.value = valNum * 3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
</div>
</div>
Added inverse conversion:
let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');
function FeetToMetres(valNum) {
metresEl.value = valNum/3.2808;
}
function MetresToFeet(valNum) {
feetEl.value = 3.2808*valNum;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
</div>
</div>
You can add a element.addEvenetListener to each input, and when it chances you get it's value, convert, and put in on the right input.
let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');
metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);
For exemple, if metres input changes, you convert to feets and add to feets input.
Related
How do i clear multiple user inputs in javascript
I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything. i want to make the reset button to clear user inputs? Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong. Please i'll appreciate if anyone can assist me with this. <div class=" DTRloading__form" style="display: block;"> <div class="form-container"> <div class="info"> </div> <form class="form-inline"> <div class="form-group w-5 "> <label for="red">Red Phase:</label> <input type="number" class="form-control formInline" id="red" style="width: 80px"> </div> <div class="form-group"> <label for="yellow">Yellow Phase:</label> <input type="number" class="form-control formInline" id="yellow" style="width: 80px"> </div> <div class="form-group"> <label for="blue">Blue Phase:</label> <input type="number" class="form-control formInline" id="blue" style="width: 80px"> </div> <div class="form-group"> <label for="neutral">Neutral:</label> <input type="number" class="form-control formInline" id="neutral" style="width: 80px"> </div> </form> <label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label> <input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required> <button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button> </div> <div class="output"> <h5 class="b-display">DTR Full Load Current is:</h5> <div id="flA" class="form-control bill"></div> <h5 class="b-display">The percentage Loading of this DTR is:</h5> <div id="outputLoading" class="form-control bill"></div> <!-- <div id="outputSum" class="form-control bill"></div>--> <button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button> </div> </div> <script> document.getElementById("btnStart3").addEventListener('click', doCalc); function doCalc() { // Assign user inputs to variables let x = parseFloat(document.querySelector("#red").value); let y = parseFloat(document.querySelector("#yellow").value); let z = parseFloat(document.querySelector("#blue").value); let n = parseFloat(document.querySelector("#neutral").value); const capacity = document.querySelector("#inputKVA"); const output2 = document.querySelector("#outputLoading"); const output3 = document.querySelector("#flA"); const start3 = document.getElementById("btnStart3"); const refresh3 = document.getElementById("btnRefresh3"); // // Call the average function getAverage(x,y,z,n); } function getAverage(x,y,z,n) { // Calculate the average let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100); // Display result to user console.log(average); outputLoading.innerHTML = average.toFixed(0) + "%"; // } const capacity = document.querySelector("#inputKVA"); function calculate(e) { console.log(e); e.preventDefault(); console.log("btnStart3 clicked"); var totalfLA = ((capacity.value * 1000) / (1.7321 * 415)); console.log(totalfLA); flA.innerHTML = totalfLA.toFixed(1) + "A"; } function emptyInput() { console.log("emptied!"); outputKVA.innerHTML = ""; flA.innerHTML = ""; x.value = ""; y.value = ""; z.value = ""; n.value = ""; capacity.value = ""; output2.value = ""; output3.value = ""; } btnStart3.addEventListener("click", calculate); refresh3.addEventListener("click", emptyInput); </script>
You can try in html with below button type as well. <input type="reset" value="Reset"> If you want reset form from javascript then document.getElementById("your-form-id").reset(); Change 1. <form class="form-inline"> 2. refresh3.addEventListener("click", emptyInput); to 1. <form class="form-inline" id="form"> 2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput); 3. function emptyInput() { document.getElementById("form").reset(); }
how to have numbers output with commas
I am trying to create a simple mortgage calculator and I want to have the numbers print with commas when the outputted number is larger than 3 digits. I would appreciate any help or suggestions. Im not really good at JS so I'd appreciate an example of where I'd put the code to allow it to print a comma. Thank you guys! JS Code var results; function clearResults() { $(".form__error").html(""); $('.results').html(""); }; $(function(){ $('body').on('submit','form',{},function(e){ e.preventDefault(); // clear previous results clearResults(); // get our inputs var rawInputs = $(this).serializeArray(); // convert these to numbers and create our argument array var args = {}; for(var i = 0; i < rawInputs.length; i++) { args[rawInputs[i].name] = parseFloat(rawInputs[i].value); } // run the mortgage calculator results = mortgageCalculators.monthlyMortgagePayments(args); if(results.error) { $(".form__error").html(results.error); } else { $('.results').html(results) } }); }); !function(){function e(e,t){var r={error:!1,data:e};for(var o in t){if(t[o].isRequired&&void 0==e[o]){r.error=o+" is required.";break}if(t[o].isNumber&&("number"!=typeof e[o]||isNaN(e[o]))){r.error=o+" must be a number.";break}if(t[o].isNotNegative&&e[o]<0){r.error=o+" must be a positive number.";break}if(t[o].isNotZero&&0==e[o]){r.error=o+" must be greater then 0.";break}if(t[o].isNotFloat&&e[o]%1!=0){r.error=o+" must be an integer value.";break}}return r}function t(e,t){return e*t}function r(e){var t=e.loanAmount,r=0==e.interestRate?0:e.interestRate/100,o=0==r?0:r/12,i=12*e.termInYears;return o*t*Math.pow(1+o,i)/(Math.pow(1+o,i)-1)}function o(e){var t=e.monthlyPrincipalPayment,r=0==e.interestRate?0:e.interestRate/100,o=0==r?0:r/12,i=12*e.termInYears;return t*(Math.pow(1+o,i)-1)/(o*Math.pow(1+o,i))}function i(e){return isNaN(parseFloat(e.toFixed(2)))?0:parseFloat(e.toFixed(2))}window.mortgageCalculators={},window.mortgageCalculators.monthlyMortgagePayments=function(t){var o=e(t,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0}});return o.error?{error:o.error}:i(r(t))},window.mortgageCalculators.monthlyMortgagePaymentsWithExtraPayments=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},extraPaymentAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.interestRate/100/12,n=12*o.termInYears,N=o.extraPaymentAmount,m=r({loanAmount:o.loanAmount,interestRate:o.interestRate,termInYears:o.termInYears}),u=o.loanAmount,l=0,g=m,R=0;R<=n;R++){u-(c=m-(v=t(s,u)))>=0?u>=g&&(u-=c):u-=g=u,u>0&&(l+=m)}var y=m+N;u=o.loanAmount;var d=[];for(R=0;R<=n;R++){var v,c;u-(c=m-(v=t(s,u))+N)>=0?u>=y&&(u-=c):u-=y=u,u>0&&d.push({monthlyPayment:i(m+N),principalPayment:i(c),interestPayment:i(v),balance:i(u)})}for(var b=[],f=0;f<=Math.ceil(d.length);f+=12)b.push(d.slice(f,f+12));for(var h=[],I=o.loanAmount,F=0;F<b.length;F++){for(var P=0,p=0,q=0;q<b[F].length;q++)P+=b[F][q].interestPayment,p+=b[F][q].principalPayment;I-p>=0?I>=p&&(I-=p):I-=p=I,h.push({annualInterestPayment:i(P),annualPrincipalPayment:i(p),balance:i(I),monthlyBreakdown:b[F]})}return{withExtraPayment:{totalMonthlyPayment:i(m+N),interestRate:o.interestRate,term:o.termInYears,totalCost:i(d.length*(m+N)),payments:h},withoutExtraPayment:{totalMonthlyPayment:i(m),interestRate:o.interestRate,term:o.termInYears,totalCost:i(l)}}},window.mortgageCalculators.howMuchCanIBorrow=function(t){var r=e(t,{interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},grossMonthlyIncome:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},downPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},monthlyDebtPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},yearlyPropertyTax:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},yearlyPropertyInsurance:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(r.error)return{error:r.error};var a=t.interestRate,s=t.termInYears,n=t.monthlyDebtPayment,N=t.grossMonthlyIncome,m=t.downPayment/100,u=t.yearlyPropertyTax/12+t.yearlyPropertyInsurance/12,l=.36,g=.43,R=o({termInYears:s,interestRate:a,monthlyPrincipalPayment:l*N-n-u}),y=o({termInYears:s,interestRate:a,monthlyPrincipalPayment:g*N-n-u});return{conservative:{priceOfHome:i(R+R*m),downPayment:i(R*m),loanAmount:i(R)},aggressive:{priceOfHome:i(y+y*m),downPayment:i(y*m),loanAmount:i(y)},futureMonthlyPayment:{conservative:{principalAndInterest:i(l*N-n),taxesAndInsurance:i(u),totalMonthlyPayment:i(l*N-n+u)},aggressive:{principalAndInterest:i(g*N-n),taxesAndInsurance:i(u),totalMonthlyPayment:i(g*N-n+u)}}}},window.mortgageCalculators.compareFifteenVsThirtyYearMortgages=function(t){var o=e(t,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate1:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},interestRate2:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(o.error)return{error:o.error};var a=t.loanAmount,s=t.interestRate1,n=t.interestRate2,N=r({loanAmount:a,interestRate:s,termInYears:15}),m=r({loanAmount:a,interestRate:n,termInYears:30});return{fifteenYearMortgage:{monthlyMortgagePayment:i(N),totalInterest:i(15*N*12-a),totalPayments:i(15*N*12)},thirtyYearMortgage:{monthlyMortgagePayment:i(m),totalInterest:i(30*m*12-a),totalPayments:i(30*m*12)}}},window.mortgageCalculators.refinanceMortgage=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},newInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},newTermInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},newTermInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},paymentsMade:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!0}});if(a.error)return{error:a.error};for(var s=o.loanAmount,n=o.interestRate,N=o.termInYears,m=o.newInterestRate,u=o.newTermInYears,l=o.paymentsMade,g=r({loanAmount:s,interestRate:n,termInYears:N}),R=s,y=0,d=0;d<l;d++){var v=t(n/100/12,R),c=g-v;R-c>=0&&(R-=c),c,y+=v}var b=g*N*12-s-y,f=R,h=r({loanAmount:f,interestRate:m,termInYears:u}),I=h*u*12-R;return{interestSaved:i(b-I),oldMonthlyMortgage:{monthlyMortgagePayment:i(g),remainingInterest:i(b)},newMonthlyMortgage:{newMortgageTotal:i(f),monthlyMortgagePayment:i(h),remainingInterest:i(I)}}},window.mortgageCalculators.comparefixedRateVsARM=function(o){var a=e(o,{loanAmount:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},monthsBeforeFirstAdjustment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},monthsBetweenAdjustments:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},expectedAdjustmentRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},initialInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},maximumInterestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.interestRate,n=o.termInYears,N=o.loanAmount,m=o.initialInterestRate,u=o.expectedAdjustmentRate,l=o.monthsBeforeFirstAdjustment,g=o.monthsBetweenAdjustments,R=o.maximumInterestRate,y=r({loanAmount:N,interestRate:s,termInYears:n}),d=r({loanAmount:N,interestRate:m,termInYears:n}),v=N,c=0;c<l;c++){v-=d-t(m/100/12,v)}for(var b=m+u,f=r({loanAmount:v,interestRate:b,termInYears:n-l/12}),h=0;h<g;h++){v-=f-t(b/100/12,v)}for(var I,F=12*n-l-g,P=0;P<F;P+=g){b<R?b+=u:b=R,f=r({loanAmount:v,interestRate:b,termInYears:(F-P)/12});for(var p=0;p<g;p++){v-=f-t(b/100/12,v)}I=f}return response={fixedRate:{monthlyMortgagePaymentARM:i(y)},ARM:{initialMonthlyMortgagePayment:i(d),maxMonthlyMortgagePayment:i(I)}},response},window.mortgageCalculators.compareBuyVsRent=function(o){var a=e(o,{monthlyRent:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},purchasePrice:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!1},downPayment:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},interestRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},termInYears:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},howLongBeforeSelling:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!0,isNotFloat:!0},incomeTaxRate:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},expectedAnnualRentIncrease:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},closingCosts:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1},annualAppreciation:{isRequired:!0,isNumber:!0,isNotNegative:!0,isNotZero:!1,isNotFloat:!1}});if(a.error)return{error:a.error};for(var s=o.monthlyRent,n=o.expectedAnnualRentIncrease,N=o.purchasePrice,m=o.downPayment/100*N,u=N-m,l=o.interestRate,g=o.termInYears,R=o.closingCosts/100*u,y=o.howLongBeforeSelling,d=o.incomeTaxRate,v=o.annualAppreciation,c=r({loanAmount:u,interestRate:l,termInYears:g}),b=0,f=0,h=0,I=N,F=0,P=m,p=0;p<y;p++){F+=12*s,s+=s*(n/100),I+=I*(v/100);for(var q=0;q<12;q++){var w=t(l/100/12,u),A=c-w;u-A>=0?u>=A&&(u-=A):u-=A=u,f+=A,b+=w,h+=w*(d/100)}}var Z=I-u,M=(P+=f+b-h+(u+R))-I;return{currentValueOfHome:i(I),totalOwedToBank:i(u),equityOnHome:i(Z),netCostOfBuying:i(M),netCostOfRenting:i(F),benefitOfBuying:i(F-M)}}}(); HTML <div class="loan-calculator"> <div class="top"> <h2>Monthly Mortgage Payment Calculator</h2> <br /><br/> <form action="#"> <div class="group"> <div class="title">Loan Amount</div> <input type="text" placeholder="0" name="loanAmount" id="loanAmount" > </div> <div class="group"> <div class="title" >Interest Rate</div> <input type="text" placeholder="0" name="interestRate" id="interestRate"> </div> <div class="group"> <div class="title">Term (Years)</div> <input type="text" placeholder="0" name="termInYears" id="termInYears"> </div> </div> <div class="result"> <div class="left"> <br /><br /> <h3>Monthly mortgage payment of</h3> <div class="results value"></div> <button class="calculate-btn-mortgage" type="submit">Calculate </button> <br /> <br /> </div> </div> </form>
you can write it with regex and replace number with string at show time: function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } or you can do this too: var n = 34523453.345; console.log(n.toLocaleString()); // "34,523,453.345"
Calc two fields and set results in third
I have a problem with the script. I am trying to count two input fields, and insert the result into the third field. But it doesn't work, and unfortunately I can't figure out what's wrong. function sum() { var txtFirstNumberValue = document.querySelectorAll('#firstID > div > div > div > input').value; var txtSecondNumberValue = document.querySelectorAll('#second > div > div > div > input').value; if (txtFirstNumberValue == "") txtFirstNumberValue = 0; if (txtSecondNumberValue == "") txtSecondNumberValue = 0; var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue); if (!isNaN(result)) { document.querySelectorAll('#third > div > div > div > input').value = result; } } <div id="firstID"><div> <label>first</label> <div> <div> <input name="drts[field_first][0]" type="number" value="" maxlength="255"> </div> </div> </div></div> <div id="second"><div> <label>second</label> <div> <div> <input name="drts[field_second][0]" type="number" maxlength="255"> </div> </div> </div></div> <div id="third"><div> <label>third</label> <div> <div> <input name="drts[field_third][0]" type="number" value="" maxlength="255"> <div></div> </div> </div> </div></div>
There are a few problems here. Are you actually calling sum? I've added a call in the example code so you can run it. Your query selectors are not right. There isn't actually anything in the divs with the IDs you query. I've moved the input boxes into the correct places. When debugging, you should check that you are actually finding elements in your querySelectorAll call before proceeding. querySelectorAll doesn't have a value property. You would need to iterate over each element before getting the items. Given you specifically want one item, it would be better to use something more specific like getElementById. I've kept the original querySelectorAll but changed the IDs on the divs to classes so we can have more than one result for this example. Then, I iterate over them pulling out the value to add to result. I've moved the parseInt to the running calculation otherwise it would perform a string concatenation. Even better than the above would be to access the input directly. There's probably no point accessing a div and drilling down to the input. I've included this example to output the result. I've removed redundant html. It's not related to the answer but try to keep your markup clean. function sum() { var inputElements = document.querySelectorAll('.user-input > div > div > input'); var result = 0; inputElements.forEach(element => { result += element.value ? parseInt(element.value) : 0 }) document.getElementById('third').value = result } document.getElementById('run-button').addEventListener('click', sum) <div class="user-input"> <label>first</label> <div> <div> <input name="drts[field_first][0]" type="number" maxlength="255"> </div> </div> <div> <div class="user-input"> <label>second</label> <div> <div> <input name="drts[field_second][0]" type="number" maxlength="255"> </div> </div> <div> <label>third</label> <div> <div> <input id="third" name="drts[field_third][0]" type="number" value="" maxlength="255"> <div></div> </div> </div> <div> <button type="button" id="run-button">Run</button>
Try like this function sum() { let txtFirstNumberValue = document.querySelector('#firstID input').value; let txtSecondNumberValue = document.querySelector('#second input').value; let result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue); if (!isNaN(result)) { document.querySelector('#third input').value = result; } else { document.querySelector('#third input').value = ''; } } <div id="firstID"><div> <label>first</label> <div> <div> <input name="drts[field_first][0]" type="number" value="" maxlength="255"> </div> </div> </div></div> <div id="second"><div> <label>second</label> <div> <div> <input name="drts[field_second][0]" type="number" maxlength="255"> </div> </div> </div></div> <div id="third"><div> <label>third</label> <div> <div> <input name="drts[field_third][0]" type="number" value="" maxlength="255" disabled> <div></div> </div> </div> <div> <button id="button" onclick="sum()">Calculate</button> </div> </div> </div>
const input1 = document.querySelector('#input1'); const input2 = document.querySelector('#input2'); const input3 = document.querySelector('#input3'); const storeInputs = [input1, input2]; for(let i = 0; i < storeInputs.length; i++) { storeInputs[i].addEventListener('input', function() { // multiply input1 and input2 with 1 for converting there values from string to number input3.value = input1.value * 1 + input2.value * 1; }); }; <!DOCTYPE html> <html> <head> <title></title> </head> <body> <label for="input1">First Input</label> <input id="input1" type="number" value="0"></input> <label for="input2">Second Input</label> <input id="input2" type="number" value="0"></input> <label for="input3">Third Input</label> <input id="input3" type="number" value="0"></input> </body> </html>
Appending and detaching dynamically created inputs
I have two radio buttons: fixed_price_option (Selected by default.) variable_price_option (Disabled by default) I also have two types of inputs: fixed_price_input (Visable by default. Only one occurance.) variable_price_input (Not present in code as it has to be added dynamically. One or more occurances.) When fixed_price_option is selected an input called fixed_price_input should be visable and included when later running .serialize(). When fixed_price_option is selected no variable_price_input´s should be visible or included when later running .serialize(). variable_price_option should only be selectable when the difference between two date inputs are more than 12 months. (this I have solved) When variable_price_option is selected there should be one more variable_price_input´s visable as there are whole years between the two date inputs (i.e. durationMonths + 1). They also need to be included when later running .serialize() so they need to have names like price_year_1, price_year_2, price_year_3 and so on, depending on how many whole years there are between the two date inputs. When variable_price_option is selected fixed_price_input should not be visible or included when later running .serialize(). I have supplied the code as far as I have come. The missing logic needs to be put in the event handler at the bottom of the js code. Any suggestions on how to solve this? -- UPDATE -- My question needed clarification: What I'm struggling with is to toggle the existence of the two types of inputs (fixed_price_input and variable_price_input) depending on which radio button is checked. Hiding/showing them isn't enough because I'm going to use .serialize() at a later point. Should I use .detach() and .append() somehow? I'm also struggling with how to create one more variable_price_input's than there are years between the start and end date. Should I use <template> or .clone() somehow? $(document).ready(function() { $("#inputStartDate, #inputEndDate").change(function() { if ($('#inputStartDate').val() && $('#inputEndDate').val()) { var startDate = moment($('#inputStartDate').val()); var endDate = moment($('#inputEndDate').val()); var durationMonths = endDate.diff(startDate, 'months'); $('#durationMonths').text(durationMonths); var durationYears = endDate.diff(startDate, 'years'); $('#durationYears').text(durationYears); if (duration > 12) { $('#variablePriceOption').prop("disabled", false); } else { $('#variablePriceOption').prop("disabled", true); } } }); $('#variablePriceOption, #fixedPriceOption').change(function() { if (this.value == 'fixedPrice') { //Logic needed } else if (this.value == 'variablePrice') { //Logic needed } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <div class="container"> <div class="row mt-3"> <div class="col"> <div class="form-group"> <label for="inputStartDate">Start date</label> <input type="date" class="form-control" id="inputStartDate" name="land_contract_start_date"> </div> </div> <div class="col"> <div class="form-group"> <label for="inputEndDate">End date</label> <input type="date" class="form-control" id="inputEndDate" name="land_contract_end_date"> </div> </div> </div> <div class="text-center">Months between selected dates = <span id="durationMonths"></span>. Years between selected dates = <span id="durationYears"></span>. </div> <div class="form-group"> <label for="inputPriceModel">Price model</label> <div id="inputPriceModel"> <div class="form-check"> <input class="form-check-input" type="radio" name="inputPriceModel" id="fixedPriceOption" value="fixedPrice" required checked="checked"> <label class="form-check-label" for="fixedPriceOption"> Fixed price </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="inputPriceModel" id="variablePriceOption" value="variablePrice" disabled="disabled"> <label class="form-check-label" for="variablePriceOption"> Variable price </label> </div> </div> </div> <div class="form-group fixedPriceModelFormGroup"> <label for="fixed_price_input">Fixed price amount</label> <div class="input-group"> <input type="number" class="form-control" id="fixed_price_input" name="land_contract_fixed_annual_price"> <div class="input-group-append"> <span class="input-group-text">$</span> </div> </div> </div> </div>
This should help get you started as far as variable pricing inputs showing for each # of year difference of the calendar dates. The code could be broken out into other functions for handling the display/hiding of elements, etc. You need to move your <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> code above your other JS references to get rid of the errors you're seeing for bootstrap. Also, your duration variable should be durationMonths for comparing > 12, as duration is undefined. durationYears should be moved outside the change function of the calendar dates so you can reference it in your other processing functions. I added Math.abs() to the date calculations to ensure you're dealing with a positive integer for comparisons. Using the disabled attribute on the inputs that are hidden will allow you to serialize the visible form data and ensure you won't get hidden inputs (variable pricing fields, etc) as part of the serialization data. As #Twisty mentioned in the comments on your post, you will want to use .detach() or some sort of way to store the variable pricing input values if you toggle back and forth between Fixed/Variable options (localStorage, sessionStorage also options for storing data), if you want to maintain any values placed in the variable/fixed inputs. You will need to remove the .empty() usage on the input fields in my example as well, if you intend to store the data values of the inputs. The loop function handleVariablePricing for determining how many variable pricing inputs should show would need to hook into the stored data functionality to ensure you are creating the same amount of fields with previously entered values, and not adding additional new fields on top of the existing fields/values. $(document).ready(function() { var durationYears = 0; $("#inputStartDate, #inputEndDate").change(function() { if ($('#inputStartDate').val() && $('#inputEndDate').val()) { var startDate = moment($('#inputStartDate').val()); var endDate = moment($('#inputEndDate').val()); var durationMonths = Math.abs(endDate.diff(startDate, 'months')); $('#durationMonths').text(durationMonths); // maintain value outside of change function durationYears = Math.abs(endDate.diff(startDate, 'years')); $('#durationYears').text(durationYears); if (durationMonths > 12) { $('#variablePriceOption').prop("disabled", false); } else { $('#variablePriceOption').prop("disabled", true); } // If dates changed, update variable inputs shown if ($('#variablePriceOption').is(':checked')) { if (durationMonths > 12) { $('#variable_price_input_1').val(''); $('.duration-years-input').remove(); handleVariablePricing(); } else { $('#fixedPriceOption').click(); } } } }); $('#variablePriceOption, #fixedPriceOption').change(function() { if (this.value == 'fixedPrice') { $('.variablePriceModelFormGroup').removeClass('d-block').addClass('d-none'); $('.variablePriceModelFormGroup input').each(function() { $(this).val('').attr('disabled', true); }); $('.fixedPriceModelFormGroup input').prop('disabled', false); $('.fixedPriceModelFormGroup').removeClass('d-none').addClass('d-block'); $('.duration-years-input').remove(); } else if (this.value == 'variablePrice') { $('.fixedPriceModelFormGroup').removeClass('d-block').addClass('d-none'); $('.fixedPriceModelFormGroup input').val('').attr('disabled', true); $('#variable_price_input_1').prop('disabled', false); $('.variablePriceModelFormGroup').removeClass('d-none').addClass('d-block'); handleVariablePricing(); } }); /** * Creates inputs for variable pricing.. **/ var handleVariablePricing = function() { $rowClone = $('.row-main').clone(); for (var i = 2; i <= durationYears + 1; i++) { $rowClone.prop('class', 'duration-years-input'); $rowClone.find('label').text('Price Year ' + i); $rowClone.find('input').prop('id', 'variable_price_input_' + i); $rowClone.find('input').prop('name', 'land_contract_variable_annual_price_' + i); if ($('.duration-years-input').length === 0) { $('.row-main').after($rowClone); } else { $('.duration-years-input').last().after($rowClone); } $rowClone = $('.duration-years-input').last().clone(); } }; $('button').click(function() { console.log($('#test-form').serialize()); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <div class="container"> <form id="test-form"> <div class="row mt-3"> <div class="col"> <div class="form-group"> <label for="inputStartDate">Start date</label> <input type="date" class="form-control" id="inputStartDate" name="land_contract_start_date"> </div> </div> <div class="col"> <div class="form-group"> <label for="inputEndDate">End date</label> <input type="date" class="form-control" id="inputEndDate" name="land_contract_end_date"> </div> </div> </div> <div class="text-center">Months between selected dates = <span id="durationMonths"></span>. Years between selected dates = <span id="durationYears"></span>. </div> <div class="form-group"> <label for="inputPriceModel">Price model</label> <div id="inputPriceModel"> <div class="form-check"> <input class="form-check-input" type="radio" name="inputPriceModel" id="fixedPriceOption" value="fixedPrice" required checked="checked"> <label class="form-check-label" for="fixedPriceOption"> Fixed price </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="inputPriceModel" id="variablePriceOption" value="variablePrice" disabled="disabled"> <label class="form-check-label" for="variablePriceOption"> Variable price </label> </div> </div> </div> <div class="form-group fixedPriceModelFormGroup"> <label for="fixed_price_input">Fixed price amount</label> <div class="input-group"> <input type="number" class="form-control" id="fixed_price_input" name="land_contract_fixed_annual_price"> <div class="input-group-append"> <span class="input-group-text">$</span> </div> </div> </div> <div class="form-group variablePriceModelFormGroup d-none"> <div class="row-main"> <label for="variable_price_input">Price Year 1</label> <div class="input-group"> <input type="number" class="form-control" id="variable_price_input_1" name="land_contract_variable_annual_price_1" disabled="disabled"> <div class="input-group-append"> <span class="input-group-text">$</span> </div> </div> </div> </div> </form> <button>Serialize</button> </div>
I have just formatted numbers to appear with commas but now my calculator doesn't work?
I am building a calculator, which I have previously asked questions on, see previous link: Building an interest rate calculator, however it won't produce figure I want some fields to appear with commas when entered, I found some code on here and it seems to work with the formatting however now the calculations just return NaN. Any ideas why adding commas would stop it from working? Here's the code I used to add the commas and the code for the calculator is on the previous link: HTML: <div class="col-md-10 col-md-offset-1 form-body form-group"> <h2 class="form-heading">Find out how much your mortgage will cost</h2> <div class="row text-muted"> <div class="col-md-5 col-md-offset-1 calc-input"> <h3>Purchase Price</h3> <div class="input-group"> <span class="input-group-addon">£</span> <input type="text" class="form-control comma" id="pp" placeholder="150,000" onchange="depositValue()"> </div> <h3>Deposit</h3> <div class="row text-muted"> <div class="col-md-4"> <div class="input-group"> <input type="text" class="form-control" id="percent" placeholder="10" onchange="depositValue()"> <span class="input-group-addon">%</span> </div> </div> <div class="col-md-8"> <div class="input-group"> <span class="input-group-addon">£</span> <input type="text" class="form-control comma" id="dp" placeholder="15,000" onchange="depositPercent()"> </div> </div> </div> <h3>Mortgage Term</h3> <div class="input-group"> <input type="text" class="form-control" id="mt" placeholder="25"> <span class="input-group-addon">Years</span> </div> <h3>Interest Rate</h3> <div class="input-group"> <input type="text" class="form-control" id="ir" placeholder="4"> <span class="input-group-addon">%</span> </div> </div> <div class="col-md-5 text-center"> <h3>Estimated Monthly Payment:</h3> <p id="result"></p> </div> </div> <div class="row text-muted"> <div class="col-md-10 col-md-offset-1 text-center"> <button class="btn btn-cta" onclick="calculate()">Calculate</button> </div> </div> </div> Calculator JS: function calculate() { var pp = document.getElementById("pp").value; var dp = document.getElementById("dp").value; var mt = document.getElementById("mt").value; var ir = document.getElementById("ir").value; var result = document.getElementById("result"); var la = parseInt(pp.replace(/,/g, ""), 10) - parseInt(dp.replace(/,/g, ""), 10); var intRate = (ir/100)/12; var months = mt * 12; var monthlyPayment = ((((la*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100).toFixed(2)); result.innerHTML = "£" + monthlyPayment.replace(/\B(?=(\d{3})+(?!\d))/g, ","); } function depositValue() { var pp = document.getElementById("pp").value; var percent = document.getElementById("percent").value; var dp = document.getElementById("dp"); var dpValue = (parseInt(percent.replace(/,/g, ""), 10) / 100) * parseInt(pp.replace(/,/g, ""), 10); dp.value = dpValue; } function depositPercent() { var pp = document.getElementById("pp").value; var dp = document.getElementById("dp").value; var percent = document.getElementById("percent"); var dpPercent = (parseInt(dp.replace(/,/g, ""), 10) / parseInt(pp.replace(/,/g, ""), 10) * 100).toFixed(0); percent.value = dpPercent; } Comma JS (in another file): $('input.comma').keyup(function(event) { // skip for arrow keys if(event.which >= 37 && event.which <= 40) return; // format number $(this).val(function(index, value) { return value .replace(/\D/g, "") .replace(/\B(?=(\d{3})+(?!\d))/g, ",") ; }); });
The moment you add the commas, it's no longer a number, but a string. When you do your calculations you'll have to account for that by stripping them out before processing.