Hello I am attempting to create a user friendly application that allows the user to buy pencils, pens, and erasers. A total cost should be displayed.
My code mostly works except for one problem. the numbers that the user inputs in the boxes (how many pens/pencils/erasers they would like to buy) are not being used by the code. if I add a value manually to the code it performs the calculation (<input type="number" value="3" placeholder="# of erasers" min="0" id="numOfErasers">) could somebody please help me with getting the calculation to use user inputted numbers?
here's my code (JavaScript/HTML):
<!DOCTYPE html>
<html>
<head>
<title> Pencils Pens Erasers </title>
<script>
//this is the function that calcultes the cost
function costCalculator () {
var total = penCost + pencilCost + eraserCost;
return total;
}
</script>
</head>
<body>
<form>
<!--this is the order form-->
<br>
<u><b>please indicate how many of each you wish to order:</b></u>
<br><br>
Pens:<input type="number" placeholder="# of pens" min="0" id="numOfPens">
Pencils:<input type="number" placeholder="# of pencils" min="0" id="numOfPencils">
Erasers:<input type="number" placeholder="# of erasers" min="0" id="numOfErasers">
<br><br>
please select which province you are ordering from:<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan </option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select>
</form>
<script>
//these are all my variables
var pens = document.getElementById("numOfPens").value
var pencils = document.getElementById("numOfPencils").value
var erasers = document.getElementById("numOfErasers").value
var penCost = 0.50 * pens
var pencilCost = 0.30 * pencils
var eraserCost = 1.00 * erasers
var province = document.getElementById("whichProvince").value
var totalCost = costCalculator()
//this code adds taxes and discount to the total price based on province
if (province == 1) {
totalCost = (5 / 100) * totalCost + totalCost;
} else if (province == 1 && totalCost>30) {
totalCost = totalCost-5
} else if (province == 2) {
totalCost = (5 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
} else if (province == 3) {
totalCost = (6 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
}
/* function test () {
window.alert(total)
}
*/
function test2 () {
window.alert(totalCost)
}
document.write ("<br>" + " The total cost of your purchase will be: " + "<b>" + totalCost + "</b>" + "<br>")
</script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p><p align=center>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator(); test2();" >
</p>
</body>
</html>
As said in the comments you need to get familiar with events (this is another good resouce). The example below is a minimal working example, you can use that as reference when creating mininal reproducible examples.
The main difference is that it uses a button at the end with onclick attribute calling the costCalculator function.
function costCalculator() {
var pensTotal = document.getElementById("numOfPens").value * 0.5;
var pencilsTotal = document.getElementById("numOfPencils").value * 0.3;
var erasersTotal = document.getElementById("numOfErasers").value;
var total = parseFloat(pensTotal + pencilsTotal + erasersTotal);
var province = document.getElementById("whichProvince").value;
if (province == 1) {
total = (5 / 100) * total + total;
if (total > 30) {
total -= 5;
}
} else if (province == 2) {
total = (5 / 100) * total + total;
total += 2;
} else if (province == 3) {
total = (6 / 100) * total + total;
total += 2;
}
document.getElementById("output").innerHTML = total;
}
<label for="numOfPens">Pens:</label>
<input type="number" placeholder="# of pens" min="0" id="numOfPens"><br/>
<label for="numOfPencils">Pencils:</label>
<input type="number" placeholder="# of pencils" min="0" id="numOfPencils"><br/>
<label for="numOfErasers">Erasers:</label>
<input type="number" placeholder="# of erasers" min="0" id="numOfErasers"><br/>
<label for="whichProvince">please select which province you are ordering from:</label>
<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan</option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select><br/>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator()">
<p id="output"></p>
I've done a few irrelevant changes to your code, I'll answer anything you need in the comments.
Related
I have three types for tickets. Children - cost 8$, retirees - cost 10$ and adults - cost 12$ and i have 3 input numbers and i want when someone of these three input change to calculate and print in html total price
This is my html
children<input type="number" id="children" name="children" min="0" max="20" value="0" onchange="myScript">
adults<input type="number" id="adults" name="adults" min="0" max="20" value="0" onchange="myScript">
retirees<input type="number" id="retirees" name="retirees" min="0" max="20" value="0" >
This is my js
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var children = document.getElementsByName('adults');
var children = document.getElementsByName('retirees');
total = (parseInt(children) * 8) + (parseInt(adults) * 12) + (parseInt(retirees) * 10);
Here i dont know how to print in html total price
I want to look something like that
One possible way is to place a div for displaying Total in html
<div id="total"></div>
then attach an "eventListener" for change to each input field to trigger the calculation
document.querySelectorAll("input").forEach(el => {
el.addEventListener("change", () => {
totalPrice();
});
});
then update the value in html with:
totalDiv.innerHTML = `<h3>Total: ${total}$</h3>`;
Working Stackblitz
Given a div below the <inputs>, in the form of <div id="price"></div>
You could set the price this way:
let price_div = document.querySelector("#price")
// Apply whatever formatting to the price you want.
price_div.innerHTML = total
As these are input fields you can just use their value
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var adults = document.getElementsByName('adults');
var retirees = document.getElementsByName('retirees');
total = (parseInt(children.value) * 8) + (parseInt(adults.value) * 12) + (parseInt(retirees.value) * 10);
function totalPrice(){
var total = 0
var children = document.getElementsByName('children')[0].value;
var adults = document.getElementsByName('adults')[0].value;
var retirees = document.getElementsByName('retirees')[0].value;
total = (children * 8) + (adults * 12) + (retirees * 10);
console.log(total);
document.getElementById('totalPrice').textContent=total;
}
children <input type="number" id="children" name="children" min="0" max="20" value="0" onKeyUp="totalPrice()">
adults <input type="number" id="adults" name="adults" min="0" max="20" value="0" onKeyUp="totalPrice()">
retirees <input type="number" id="retirees" name="retirees" min="0" max="20" value="0" onKeyUp="totalPrice()">
<div id="totalPrice" style="color:red"></div>
Ive been trying to add a discount to price classes for a couple of days now but haven’t been able to. The current js code I have is a simple addition calculator, but I want it to discount prices between 100 and 500 with 10% and prices over 500 get 20% discount. I also want it to show the price before and after the discount if possible.
The code I have for the calculator so far, its working fine:
function calculate() {
var field1 = document.getElementById("num1").value;
var field2 = document.getElementById("num2").value;
var result = parseFloat(field1) + parseFloat(field2);
if (!isNaN(result)) {
document.getElementById("answer").innerHTML = "Totalpris är " + result;
}
}
Artikel 1 <input type="text2" id="num1">
<br>
<br> Artikel 2 <input type="text2" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<h1 id="answer"></h1>
This is pretty simple to do with some if statements.
function calculate() {
var field1 = document.getElementById("num1").value;
var field2 = document.getElementById("num2").value;
var beforeDiscount = parseFloat(field1) + parseFloat(field2);
var afterDiscount = beforeDiscount;
if (beforeDiscount >= 100 && beforeDiscount < 500) {
afterDiscount = beforeDiscount * 0.9;
} else if (beforeDiscount >= 500) {
afterDiscount = beforeDiscount * 0.8;
}
if (!isNaN(beforeDiscount)) {
document.getElementById("answer").innerHTML =
"Totalpris är "+afterDiscount+". Was "+beforeDiscount;
}
}
Artikel 1 <input type="text2" id="num1">
<br>
<br>
Artikel 2 <input type="text2" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<h1 id="answer"></h1>
You should give type number
text2 is not a valid value for the type attribute
Instead of this
Artikel 1 <input type="text2" id="num1">
<br>
<br>
Artikel 2 <input type="text2" id="num2">
Do this
<input type ="number" id="num1">
<input type="number" id="num2">
Here is the solution for your challenge
<!DOCTYPE html>
<html>
<head>
</head>
<body>
a.htmlArtikel 1 <input id="num1" type="number">
<br>
<br>
Artikel 2 <input type="number" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<script>
function calculate(){
let result = ``;
const field1 = document.getElementById("num1").value;
const field2 = document.getElementById("num2").value;
let amount_before_discount = parseFloat(field1)+parseFloat(field2);
let amount_after_discount = amount_before_discount
if(amount_after_discount >= 100 && amount_before_discount < 500){
amount_after_discount = amount_before_discount * 0.9;
// for the second question, look at the comments
result += `After an discount of 10% the new price is
${amount_after_discount}`
}else if(amount_before_discount >= 500){
amount_after_discount = amount_before_discount * 0.8;
result += `After an discount of 20% the new price is
${amount_after_discount}`
}
if (!isNaN(amount_before_discount)) {
// here you can innerHtml then the result
document.getElementById("answer").innerHTML =
"Totalpris är "+amount_after_discount+". Was "+amount_before_discount;
}
}
</script>
<h1 id="answer"></h1>
</body>
</html>
I'm creating an HTML page for a restaurant bill calculator but i'm having issues with the javascript/input/form and have been stuck for a while. I'm not sure why my function is not working when I submit. If anyone has any ideas where i'm going wrong, I would greatly appreciate any help!
Here is my current code (it has to be in one HTML document):
<body>
<h1>Restaurant Bill Calculator</h1>
<br>
<form name="billcalculator" method=post onsubmit="calculateBill()">
<div class="wrapper">
<label for="tax">Tax Percent:</label>
<input type="number" id="taxPercent" min="0" max="100" step=".01">%
<br>
<label for="price">Price from the menu:</label>
<input type="number" id="menuPrice" min="0" max="1000" step=".01">
<br>
<label for="tip">Tip Percent:</label>
<input type="number" id="tipPercent" min="0" max="200" step=".01">%
<br>
<input type="submit" onclick="calculateBill()" id="submit" value="Calculate Bill">
<br>
</div>
</form>
<p id="display">Please click Calculate Bill after completing form.</p>
<script>
function calculateBill() {
var tax = document.getElementById("taxPercent")
var price = document.getElementById("menuPrice")
var tip = document.getElementById("tipPercent")
var taxamount = price * tax;
var tipamount = price * tip;
var total = taxamount + tipamount + price;
if (!tax.checkValidity()) {
window.alert(tax.validatonMessage);
}
if (!price.checkValidity()). {
window.alert(price.validationMessage);
}
if (!tip.checkValidity()) {
window.alert(tip.validationMessage);
}
if (tax.checkValidity() && price.checkValidity() && tip.checkValidity()) {
document.getElementById("display").innerHTML = "Price: $" + price.toFixed(2) + "\n" + "Tax: $" + taxamount.toFixed(2) + "\n" + "Tip: $" + tip.toFixed(2) + "\n" + "Total: $" + total.toFixed(2);
}
return true;
}
</script>
You need to get and parse the values.
var tax = parseFloat(document.getElementById("taxPercent").value);
var price = parseFloat(document.getElementById("menuPrice").value);
var tip = parseFloat(document.getElementById("tipPercent").value);
Since you have no action in your form, and are not posting anywhere, you can just remove the post method from <form>.
You should also remove the onclick function from your input. There is no reason to have both an onclick and onsubmit handler pointing to the same function.
Then add this to your calculateBill function:
function calculateBill(e) {
e.preventDefault();
Finally, you should be getting the values out of the DOM elements like so:
var tax = document.getElementById("taxPercent").value;
These will be strings, so you will have to use parseInt.
I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
Hi I am doing autosum in javascript which is working fine here in this link http://maatren.com/auto-sum.html but I want reverse autosum also.
Both are working fine but seperately. they are not working fine together.
I use this code
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
third = document.autoSumForm.thirdBox.value;
document.autoSumForm.thirdBox.value = (one * 1) + ((two / 100) * one);
//document.autoSumForm.firstBox.value = (third * 1) - ((two / 100) * third);
}
function stopCalc(){
clearInterval(interval);
}
My html is
<div style="width: 200px; text-align: center;">
<form name="autoSumForm">
<input class="right" type=text name="firstBox" value="" onFocus="startCalc();" onBlur="stopCalc();"><br>
% <input class="right" type=text name="secondBox" value="10" onFocus="startCalc();" onBlur="stopCalc();"><br>
= <input class="right" type=text name="thirdBox" value="" onFocus="startCalc();" onBlur="stopCalc();"><br>
</form>
</div>
The problem is that when i remove comment from third box then it tops working. I want autosum and reverse autosum both at same time.
<div style="width: 200px; text-align: center;">
<form name="autoSumForm">
<input class="right" type=text name="firstBox" value="" onkeyup="calc(1);"><br>
% <input class="right" type=text name="secondBox" value="10" onkeyup="calc(2);"><br>
= <input class="right" type=text name="thirdBox" value="" onkeyup="calc(3);"><br>
</form>
</div>
.
function calc(box){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
third = document.autoSumForm.thirdBox.value;
if(box == 1){
document.autoSumForm.thirdBox.value = (one * 1) + ((two / 100) * one);;
}else if(box == 2 || box == 3){
document.autoSumForm.firstBox.value = (third * 1) - ((two / 100) * third);
}
}