How to make calculations from the inputs on change? - javascript

<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->
Calculate will be like this ;
The days between checkin and checkout will be calculated and it will be multiplied by days and price.
For example 2019-09-11 between 2019-09-13 is 2 day and if user write 200 on nightprice it will calculate this like 2x200 = 400 and will be placed at totalprice input
my question is how can i do this with jquery without refresh page.

Here's a simple jQuery way to do it. The poor-mans approach would be to just listen to any input change event and re-rerun your calculation. However, if you've got more inputs on your page / form than mentioned in this question (which you likely do) then I would use more specific selectors than simple listening to all inputs. Maybe look into a class? A form onsubmit function? There's plenty of ways to handle that.
const calculatePrice = (checkin, checkout, pricePerNight) => {
checkin = new Date(checkin);
checkout = new Date(checkout);
const dayDiff = Math.round( (checkout - checkin) / (1000 * 60 * 60 * 24 ) );
return dayDiff * pricePerNight;
};
$(document).ready( e => {
const nightPriceInput = $('input[name="nightprice"]');
const checkinInput = $('input[name="checkin"]');
const checkoutInput = $('input[name="checkout"]');
const totalPrice = $('input[name="totalprice"]');
$('input').on('change', () => {
const price = calculatePrice(checkinInput.val(), checkoutInput.val(), nightPriceInput.val());
totalPrice.val(price);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->

var startArray = $("#start").val().split("-");
var finishArray = $("#finish").val().split("-");
var yearDiff = finishArray[0] - startArray[0];
var monthDiff = finishArray[1] - startArray[1];
var dayDiff = finishArray[2] - startArray[2];
$("#price").on('change', function(){
var price = $("#price").val();
var total = ((yearDiff*365) + (monthDiff*30) + (dayDiff)) * price;
$("#total").html("$" + total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="start" type="text" name="checkin" value="2019-09-11"/>
<input id="finish" type="text" name="checkout" value="2019-09-13"/>
<input id="price" type="text" name="nightprice" value="300"/>
<div id="total">
</div>

See
<input type="text" name="checkin" value="2019-09-11" id="checkin" />
<input type="text" name="checkout" value="2019-09-13" id="checkout" />
<input type="text" name="nightprice" onkeyup="calculate(this)"/> <!-- When an user write a price -->
<input type="text" name="totalprice" id="totalprice" />
<script>
var calculate = function(element) {
// get value
var price = element.value;
var checkin = document.getElementById("checkin");
checkin = checkin.getAttribute('value').replace(/[\-]+/g,'');
var checkout = document.getElementById("checkout");
checkout = checkout.getAttribute('value').replace(/[\-]+/g,'');
var totalprice = document.getElementById('totalprice');
// difference
var difference = checkout - checkin;
// calcule final price
var finalprice = price * difference;
// set final price
totalprice.setAttribute('value', finalprice);
}
</script>

Related

I need to make calculation sheet but the calculate button not working and calculate my inputs here is my formala ((P*D)/(2*SMYS*DF*T*E))

I want to calculate this formula (PD)/(2SMYSDFT*E) but when I click calculate Botton nothing happens (ps: I am not an expert )
I put the input and then I click calculate put no answer.
I made some changes on the code but still not working . please can someone edit the code!
<body>
<label for="formulas">Choose a formula:</label>
<select name="formulas" id="formulas">
<option value="free">Pipeline Thickness</option>
</select>
<h2>Enter inputs</h2>
<label for="P">MAOP=</label>
<input type="number" id="P" name="P">
<br>
<label for="D=">Do=</label>
<input type="number" id="D" name="D" >
<br>
<label for="SMYS">SMYS=</label>
<input type="number" id="SMYS" name="SMYS">
<br>
<label for="DF">DF=</label>
<input type="number" id="DF" name="SMYS">
<br>
<label for="T">T=</label>
<input type="number" id="T" name="T">
<br>
<label for="E">E ⅉ=</label>
<input type="number" id="E" name="E ⅉ=" >
<br>
<button type="button" onclick="calculate">calculate</button>
<p id="demo"></p>
<script>
document.getElementById('calculate').addEventListener('click', function() {
var amount = document.getElementById("P").value;
var amount = +P;
var quantity = document.getElementById("D").value;
var quantity = +D;
var amount = document.getElementById("SMYS").value;
var amount = +SMYS;
var amount = document.getElementById("DF").value;
var amount = +DF;
var amount = document.getElementById("T").value;
var amount = +T;
var amount = document.getElementById("E").value;
var amount = +E;
var total = (P * D) / (2 * SMYS * DF * T * E);
document.getElementById("total").value = total;
});
</script>
</head>
</body>
</html>
</form>

Calculate the sum of dynamic cloned forms for Profit and Loss in javascript Jquery

I am trying to build a Simple Profit and Loss page for my sales. The goal is:
One row equals One client.
Add a dynamic row based on number of clients.
For each row I need to input the sale amount and cost amount, then calculate the profit for that row(client).
Calculate the sum of all rows profit.
The issue: When I add a row, the button calculates only the first DOM row and not the result of the cloned ones as well.
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate() {
var salesPnl = document.getElementsbyClassName('sale').value;
var costPnl = document.getElementsbyClassName('cost').value;
var sum = document.getElementById('total').value = salesPnl - costPnl;
}
function totalProfit() {
var totalSalesPnl = document.getElementsbyClassName('sale').value;
var totalCostPnl = document.getElementsbyClassName('cost').value;
var totalSum = document.getElementById('grandTotal').value = totalSalesPnl - totalCostPnl;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total"/>
</form>
</div>
<button id="addForm">Clone</button>
<button onclick="calculate()">calculate</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>
Thanks a lot for your help, I am only two months old regarding coding.
Have a nice day
don't use id when it's not going to be unique across the page.
re-organize your logic by moving the calculate button for each line
use document.querySelector and document.querySelectorAll
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate(button) {
var form = button.closest("form");
var salesPnl = form.querySelector('.sale').value;
var costPnl = form.querySelector('.cost').value;
var sum = salesPnl - costPnl;
form.querySelector('#total').value = sum;
return sum;
}
function totalProfit() {
var parent = document.querySelector(".originalPnlDiv");
var panels = parent.querySelectorAll("#pnl")
var grand = 0;
panels.forEach(function(panel) {
grand += calculate(panel);
})
document.querySelector("#grandTotal").innerText = grand;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total" />
<button onclick="calculate(this); return false">calculate</button>
</form>
</div>
<button id="addForm">Clone</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>

Clothing calculator using javascript

I am trying to make a calculator for a clothing shop where the user can enter 3 prices, perform the total of these 3 prices, deduct a fidelity amount, deduct tax of 15% and display the total. What i am unable to do is to display a message which says Total is...
This is the code i've tried:
<html>
<head>
<script type="text/javascript">
function Bal(){
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
</script>
</head>
<body>
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</button>
<div id='Bal'></div>
</form>
</body>
</html>
How to display a message which says 'Total is..'
Your code works but your form is submitting and you don't see the result. To prevent that from happening use preventDefault on the click event from the button.
I've amended your code slightly to separate out the inline JS from the HTML which might make it easier to follow.
function bal(event) {
event.preventDefault();
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var add = parseInt(w) + parseInt(x) + parseInt(y);
var fid = add - parseInt(z);
var bal = fid * 0.85;
document.getElementById('bal').innerText = "Total is: " + bal;
}
const submit = document.querySelector('button');
submit.addEventListener('click', bal, false);
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button>Total</button>
<div id="bal"></div>
</form>
Further documentation
addEventListener
querySelector / querySelectorAll
The browser will reload the page when you submit the form. To prevent that default action, use event.preventDefault() as follows.
<form onsubmit="event.preventDefault()">
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</button>
<div id='Bal'></div>
</form>
Try this
<html>
<head>
</head>
<body>
<h2>Body & Soul </h2>
<form onSubmit="Bal()">
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<button type="submit">Total</button>
<div id='Bal'></div>
</form>
</body>
<script type="text/javascript">
function Bal(){
event.preventDefault();
event.stopPropagation();
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
</script>
</html>
In this example, you don't have to include arguments to your function because you already grab their values within the function.
Another option would be this:
<form>
// Your code here
<button type="click" onClick="Bal()">Get Bal</button>
</form>
You should update your code with the below code.
function Bal(){
let w = document.getElementById('txtP1').value;
let x = document.getElementById('txtP2').value;
let y = document.getElementById('txtP3').value;
let z = document.getElementById('txtFid').value;
var Add = parseInt(w)+ parseInt(x)+ parseInt(y);
var Fid = Add-parseInt(z);
var Bal = Fid * 0.85;
document.getElementById('Bal').innerText = "Total is: " + Bal;
}
#total{
cursor : pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<h2>Body & Soul </h2>
<form>
Price 1: <input type="text" id="txtP1"><br>
Price 2: <input type="text" id="txtP2"><br>
Price 3: <input type="text" id="txtP3"><br>
Fidelity Amount: <input type="text" id="txtFid"><br>
<p id="total" onClick="Bal(txtP1.value,txtP2.value,txtP3.value,txtFid.value)">Total</p>
<div id='Bal'></div>
</form>
</body>
To be honest, i did not understand exactly what you mean because i copied and pasted your code into an HTML document and that worked fine :) but i guess that your problem is refreshing the page after clicking the "Total" button. am i right? for this purpose add a 'type="button"' to your button attributes to fix that. Your code is right!

Loan Calculator (jQuery) not working right

I have a loan calculator that I have built using JQuery, HTML, and CSS. It functions ok. The weird thing is I have to refresh the page in order to get it to calculate correctly. I'm not sure what I'm doing (or not doing) correctly. Would love some feedback.
$(document).ready(function() {
// variables
var amount = $('#loanAmount').val();
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
var duration = $('input[name=duration]:checked').val();
var calcButton = $('.calculate');
var resetButton = $('.reset');
var monthPay;
$('.results').addClass('hidden');
// Calculate Monthly Payment
calcButton.click(function(event) {
event.preventDefault();
monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
resetButton.click(function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
You're setting values on document.ready() - so it's even before any of examples in radio will be clicked. Move getting you values into the .click() function
And it's even more efficient to switch from deprecated .click() method to .on('click', function(){}) just in case you'll expand your form in the future
You need to put the vars inside the function that uses them
PS: In a form an input type="reset" /> will reset the form without needing script
$(document).ready(function() {
$('.results').addClass('hidden');
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
// Calculate Monthly Payment
$('.calculate').on("click", function(event) {
event.preventDefault();
var amount = $('#loanAmount').val();
var duration = $('input[name=duration]:checked').val();
var monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
$('.reset').on("click", function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
you take the values of duration and amount on pageload (document ready). if you update the values by filling them in, the variables won't get updated.
move var amount = $('#loanAmount').val(); and var duration = $('input[name=duration]:checked').val(); into the 'onClick' handler so that the amount and duration get updated once you click.

Live javascript calculation

I'm trying to configure a live caluator based on the Input of a form field.
My problem is, that I simply can not figure out how I would display the result on the Website.
<label class="contactform-label" for="contactform-member"><span class="contact_form_span">Member*:</span> </label>
<input class="contactform-input" type="text" id="contactform-member" placeholder="Member" name="member" value="" />
<span id="member-kosten">
<script type="text/javascript">document.write(ausgabe)</script>
</span>
var price = 90;
var member = document.getElementById("contactform-member").value;
var calculate = Math.sqrt(price * member);
var ausgabe = (calculate);
Use this code:
function fun(){
var price = 90;
var member = document.getElementById("contactform-member").value;
var calculate = Math.sqrt(price * member);
var ausgabe = (calculate);
document.getElementById("member-kosten").innerHTML = ausgabe;
}
<label class="contactform-label" for="contactform-member"><span class="contact_form_span">Member*:</span> </label>
<input class="contactform-input" type="text" id="contactform-member" placeholder="Member" name="member" value="" onkeyup="fun()" />
<span id="member-kosten">
</span>
Set the html of element member-kosten from the script (last line):
var price = 90;
var member = document.getElementById("contactform-member").value;
var calculate = Math.sqrt(price * member);
document.getElementById("member-kosten").innerHTML = calculate;
<label class="contactform-label" for="contactform-member"><span class="contact_form_span">Member*:</span> </label>
<input value="10" class="contactform-input" type="text" id="contactform-member" placeholder="Member" name="member" value="" />
<span id="member-kosten">
</span>

Categories