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!
Related
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've looked over a number of threads here of similar problems to little avail - I can't figure out exactly what's going wrong here. Google claims that the element I'm trying to reference is null
Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
and no matter how I've tried to fix it, it doesn't seem to work. As you can see in the js code, I've tried a number of ways of fixing it based on stuff I've found here.
Originally the <script src ="sales.js"> in the HTML file was up in the head, but I read in some pages here that putting it there can make it load before everything else and to put it down before the HTML closing tag.
Any suggestions?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
<h1>Sales Calculator</h1>
<p>Complete the form and click "Calculate".</p>
<fieldset>
<legend>
Item Information
</legend>
<label for="item">Item:</label>
<input type="text" id="item" ><br>
<label for="price">Price:</label>
<input type="text" id="price" ><br>
<label for="discount">Discount %:</label>
<input type="text" id="discount" ><br>
<label for="taxRate">Tax Rate:</label>
<input type="text" id="taxRate" ><br>
<label for="total">Discount Price:</label>
<input type="text" id="discountPrice" disabled ><br>
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br><br>
<div id="buttons">
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br></div>
</fieldset>
<pre>© Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
JS Code:
//"use strict"
var $ = function (id) {
return document.getElementById(id);
};
//window.addEventListener("DOMContentLoaded", () => {
//$("#calculate").addEventListener("click", processEntries);
//});
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("#calculate").addEventListener("click", processEntries);
});
//window.onload = function(){
//$("#calculate").addEventListener("click", processEntries);
//};
const processEntries = () => {
//Gather User Input
//var item = document.querySelector("#item").value;
var price = parseFloat(document.querySelector("#price").value).toFixed(2);
var discount = parseInt(document.querySelector("#discount").value);
var taxRate = parseInt(document.querySelector("#taxRate").value);
//Calculate Discounted Price
function discountPriceCalc(price, discount) {
const disPrice = price * (discount/100);
return disPrice.toFixed(2);
}
//Calculate Sales Tax
function salesTaxCalc(discountPrice, taxRate) {
const taxTotal = price * (taxRate/100);
return taxTotal.toFixed(2);
}
//Calculate Total
function totalCalc(discountPrice, salesTax) {
return ((Number(discountPrice) + Number(salesTax).toFixed(2)));
}
//Calculate the disabled text box values
var discountPrice = discountPriceCalc(price, discount);
var salesTax = salesTaxCalc(discountPrice, taxRate);
var Total = totalCalc(discountPrice, salesTax);
//Update Text Boxes
document.getElementById("discountPrice").value = discountPrice;
document.getElementById("salesTax").value = salesTax;
document.getElementById("total").value = Total;
//set focus to Item box after
document.getElementById("item").focus();
};
You need to get rid of the # in the getElementById call to properly locate the element.
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("calculate").addEventListener("click", processEntries);
});
<!-- 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'm just trying to input an number and then add 10% and then take that total and .08% tax. Can you please help me figure out what I'm doing wrong. I sure it is something simple I'm overlooking but I'm new to this and can't figure what is wrong.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Price tool</title>
</head>
<body>
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
<script type="text/javascript">
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
</script>
</body>
</html>
I logged the value of 'cost' in your code when I start with the value 100
var cost = (x * .1) + x;
console.log(cost);
and got a value of '10100'
But if I make sure that x is a number I get the correct value (110)
var cost = (x * .1) + Number(x);
console.log(cost);
And I get 118.8 for the total.
When you retrieve the value from your input control, it comes through as a string value.
var x = form["acertscore"].value; // x is a string
If you convert this to a number immediately you'll avoid additional problems.
var x = Number(form["acertscore"].value); // x is a number
function costCalc() {
var form = document.forms["operation_form"];
var x = Number(form["acertscore"].value);
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name="acertscore" value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
The problem is that your answer number is so long that it tries to display exponents. Because of this, the number gets treated as a string, though you've specified that the output goes into an <input> field with a type of number. Because your answer is not a number, it can't be displayed.
To resolve this, you can parse the output as a float before displaying it:
form["answerbox"].value = parseFloat(answer);
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = parseFloat(answer);
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
Hope this helps!
How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>