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.
Related
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>
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>
I'm trying to create an HTML form that has the user type in expected gain and cost into the input box, click calculate, and the form should calculate and display the net profit and ROI.
So far the form lets me input expected gain and cost, but the calculate button doesn't display the net profit and ROI in the appropriate boxes.
This is what I have so far (only relevant portions included):
// Declare variables
var projectName; // Gets user input for project name
var expectedCost; // Gets user input for cost of project
var expectedGain; // Gets user input for expected gain
var netProfit;
var returnOnInvestment;
function calcNetProfit() {
netProfit = expectedGain - expectedCost; // Calculate net profit
}
function calcReturnOnInvestment() {
returnOnInvestment = netProfit / expectedCost * 100; // Calculate Return on Investment
}
<form>
<label>Project Name</label>
<input>
<br><br>
<label>Cost</label>
<input>
<br><br>
<label>Gain</label>
<input>
<br><br>
<label>Net Profit</label>
<input>
<br><br>
<label>ROI as percentage</label>
<input>
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();"/><br />
</form>
Try to get the value of input type using: document.getElementById("demo").value,
and you can also manipulate the input box using the same line of code:
function calc() {
var projectName = document.getElementById("name").value
var expectedCost = document.getElementById("cost").value
var expectedGain = document.getElementById("gain").value
var netProfit = expectedGain - expectedCost;
document.getElementById("netprofit").value = netProfit;
var returnOnInvestment = netProfit / expectedCost * 100;
document.getElementById("roi").value = returnOnInvestment;
}
<form>
<label>Project Name</label>
<input type="text" id="name">
<br><br>
<label>Cost</label>
<input type="text" id="cost">
<br><br>
<label>Gain</label>
<input type="text"id="gain">
<br><br>
<label>Net Profit</label>
<input type="text" id="netprofit">
<br><br>
<label>ROI as percentage</label>
<input type="text" id="roi">
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calc();"/><br />
</form>
You are missing the steps on how to get the values for the gain, costs, and net profit.
Read on JavaScript DOM.
Here's the answer in a nutshell.
function calcNetProfit() {
var expectedGain = document.getElementById('gain').value;
var expectedCost = document.getElementById('cost').value;
var netProfit = expectedGain - expectedCost;
document.getElementById('netprofit').value = netProfit;
return netProfit;
}
function calcReturnOnInvestment() {
var expectedCost = document.getElementById('cost').value;
var netProfit = calcNetProfit();
var roi = netProfit / expectedCost * 100; // Calculate Return on Investment
document.getElementById('roi').value = roi;
}
<html>
<form>
<label>Project Name</label>
<input>
<br><br>
<label>Cost</label>
<input id="cost">
<br><br>
<label>Gain</label>
<input id="gain">
<br><br>
<label>Net Profit</label>
<input id="netprofit">
<br><br>
<label>ROI as percentage</label>
<input id="roi">
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();" /><br />
</form>
</html>
to get input value you must use
var projectname = document.querySelector('//id
or class of input id
mustbe #idname and class .classname').value;
and then manipulate with thouse values
also input tag must have type and class or id
<input type="number" class="classname">
<!-- 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>
I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()