javascript simple calculator not returning value - javascript

I am using a simple calculator form and i am trying to use javascript to calculate the total. I have referenced the source and ID's correct, however i will upload.
When clicking the calculate button the page refreshes the values back to normal.
see below for HTML and JS
function calculate() {
'use strict';
var total;
var quantity = document.getElementsById('quantity').value;
var unitPrice = document.getElementById('price').value;
var theVat = document.getElementById('vat').value;
var theDiscount = document.getElementById('discount').value;
total = quantity * unitPrice;
total = total + (total * theVat / 100) - (total * theDiscount / 100);
total = total.toFixed(2);
document.getElementById('total').value = "£" + total;
return false;
}
function initCal() {
'use strict';
document.getElementById('theCalculatorForm').onsubmit = calculate;
}
window.onload = initCal;
<!doctype html>
<html class="no-js" lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Innovative Multimedia - Simple Calculator</title>
<link rel="stylesheet" href="css/foundation.min.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div class="container">
<div class="row columns text-center">
<h2>Innovative Multimedia - Introduction to JavaScript</h2>
<p> In this application the user will enter the required details and the application will calculate the total cost.</p>
</div>
<div class="row">
<h3> Simple Calculator</h3>
<form action="" method="post" id="theCalculatorForm">
<fieldset>
<p>Use this form to calculate the order total.</p>
<div><label for="quantity">Quantity</label><input type="number" name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="number" name="price" id="price" value="1.00" required></div>
<div><label for="vat">VAT (%)</label><input type="number" name="vat" id="vat" value="17" required disabled></div>
<div><label for="discount">Discount (%)</label><input type="number" name="discount" id="discount" value="10" required disabled></div>
<div><label for="total">Total</label><input type="text" name="total" id="total" value="0" required disabled></div>
<div><input type="submit" value="Calculate" id="submitCal"></div>
</fieldset>
</form>
</div>
</div>
<script src="js/calculator.js"></script>
<script src="js/jquery.js"></script>
<script src="js/what-input.js"></script>
<script src="js/foundation.js"></script>
<script src="js/app.js"></script>
</body>
</html>
If you need anything please ask.

<form> we use it to send data by two methods (post/get) so when you click
in Button calculate all values sends and page refreshed
use div for exemple to not refresh the web page
replace the form tag with div
like this
<div id="theCalculatorForm">
</div>
<!---- Your code after will be like this ------>
<div id="theCalculatorForm">
<fieldset>
<p>Use this form to calculate the order total.</p>
<div><label for="quantity">Quantity</label><input type="number" name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="number" name="price" id="price" value="1.00" required></div>
<div><label for="vat">VAT (%)</label><input type="number" name="vat" id="vat" value="17" required disabled></div>
<div><label for="discount">Discount (%)</label><input type="number" name="discount" id="discount" value="10" required disabled></div>
<div><label for="total">Total</label><input type="text" name="total" id="total" value="0" required disabled></div>
<div><input type="submit" value="Calculate" id="submitCal"></div>
</fieldset>
</div>

In your calculate function, take one event parameter and prevent the default action from occurring:
function calculate(event) {
event.preventDefault();
//other code will work
}
Then use an event in your call:
<button onclick="calculate(e)">Calculate</button>
And it will work

Related

How properly round a number?

I need to round or fix it somehow, so the numbers comes out properly in the form.
I have tried to use toPrecision(), but I`ve never done it before and can't find a good understandable way to use it. On the screenshot is my issue.
const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50;
const pst = .07;
const gst = .07
let subtotal = 0;
////////////////Pizza size calculation///////////////
function calculateSize(element) {
if (element == null) {
return;
}
switch(element.value) {
case "10":
subtotal = priceSmall;
break;
case "12":
subtotal = priceMedium;
break;
case "15":
subtotal = priceLarge;
break;
}
recalculateTotal();
}
/////////////Topping calculation////////////
function toppingOptionPrice(element) {
if (element.checked) {
subtotal += priceToppings;
} else {
subtotal -= priceToppings;
}
recalculateTotal();
}
////////////Total//////////////
function recalculateTotal() {
let pstToPay = subtotal * pst;
let gstToPay = subtotal * gst;
let total = subtotal + pstToPay + gstToPay;
document.getElementById("subtotal").value = subtotal.toFixed(2);
document.getElementById("pstToPay").value = pstToPay.toFixed(2);
document.getElementById("gstToPay").value = gstToPay.toFixed(2);
document.getElementById("total").value = total.toFixed(2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pizza Order Form</title>
<link rel="stylesheet" href="css/style.css">
<script src="scripts/script.js"></script>
<body>
<header>
<img src="media/pizza-served.jpg" width="600" height="277" alt="Pizza Logo"/>
<h1>Pizza Order Form</h1>
</header>
<form id="myForm" name="myForm" method="post" action="http://lavalamp.dyndns.org/~mult114/pizzaorder_olympic.php" onsubmit="return validateForm();" target="_blank">
<input type="hidden" name="difficulty" value="1" />
<fieldset id="contactinfo">
<legend style="font-size: larger;"><strong>Contact Information</strong></legend>
<label for="firstnameinput">First Name</label>
<input type="text" id="firstnameinput" name="FirstName_tf" /><br>
<label for="lastnameinput">Last Name</label>
<input type="text" id="lastnameinput" name="LastName_tf" /><br>
<label for="addrinput">Address</label>
<input type="text" id="addrinput" name="Address_tf" /><br>
<label for="phoneinput">Phone</label>
<input type="text" id="phoneinput" name="Phone_tf" /><br>
<label for="emailinput">Email Address</label>
<input type="email" id="emailinput" name="Email_tf" />
</fieldset>
<fieldset id="orderinfo">
<legend style="font-size: larger;"><strong>Order</strong></legend>
<fieldset id="pizzasize">
<legend>Pizza Size</legend>
<input type="radio" id="smallsize" name="Size_rg" value="10" onclick="calculateSize(this);">
<label for="smallsize">Small 10"</label><br>
<input type="radio" id="mediumsize" name="Size_rg" value="12" onclick="calculateSize(this);">
<label for="mediumsize">Medium 12"</label><br>
<input type="radio" id="largesize" name="Size_rg" value="15" onclick="calculateSize(this);">
<label for="largesize">Large 15"</label>
</fieldset>
<fieldset id="toppingbox">
<legend>Topping(s)</legend>
<input type="checkbox" id="anchovies" name="Anchovies_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="anchovies">Anchovies</label><br>
<input type="checkbox" id="doublecheese" name="DoubleCheese_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="doublecheese">Double Cheese</label><br>
<input type="checkbox" id="pepperoni" name="Pepperoni_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="pepperoni">Pepperoni</label><br>
<input type="checkbox" id="mushrooms" name="Mushroom_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="mushrooms">Mushrooms</label><br>
</fieldset>
<fieldset id="instructions">
<legend>Special Instructions</legend>
<textarea id="textarea" name="instructions" rows="5" cols="50" placeholder="Enter your message here!(special requests, delivery details, etc.)"></textarea>
</fieldset>
</fieldset>
<fieldset id="payments">
<legend style="font-size: larger;"><strong>Payment</strong></legend>
<label>Select Payment Method:</label>
<select id="paymethods" name="Payment_menu" required="required">
<option value="select">- Select One -</option>
<option value="cash">Cash</option>
<option value="debit">Debit</option>
<option value="credit">Credit Card</option>
</select>
</fieldset>
<fieldset id="calcprice">
<legend style="font-size: larger;"><strong>Order Total</strong></legend>
<label for="subtotal">SubTotal $:</label>
<input type="text" id="subtotal" name="SubTotal_tb" readonly><br>
<label for="pstToPay">PST $:</label>
<input type="text" id="pstToPay" name="PST_tb" readonly><br>
<label for="gstToPay">GST $:</label>
<input type="text" id="gstToPay" name="GST_tb" readonly><br>
<label for="total">Total $:</label>
<input type="text" id="total" name="Total_tb" readonly><br>
</fieldset>
<input type="submit" name="Submit_but">
</form>
</body>
</html>
your code is correct. you are getting wrong because of the calculation. Try with this equation:-
let pstToPay = subtotal * pst;
pstToPay = parseFloat(pstToPay.toFixed(2));
let gstToPay = subtotal * gst;
gstToPay = parseFloat(gstToPay.toFixed(2));
And if you want to remove zeroes you can solve it by this:
.toFixed(2).replace(/0+$/, "") // this will make 4.50 = 4.5
const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50;
const pst = .07;
const gst = .07
let subtotal = 0;
////////////////Pizza size calculation///////////////
function calculateSize(element) {
if (element == null) {
return;
}
switch(element.value) {
case "10":
subtotal = priceSmall;
break;
case "12":
subtotal = priceMedium;
break;
case "15":
subtotal = priceLarge;
break;
}
recalculateTotal();
}
/////////////Topping calculation////////////
function toppingOptionPrice(element) {
if (element.checked) {
subtotal += priceToppings;
} else {
subtotal -= priceToppings;
}
recalculateTotal();
}
////////////Total//////////////
function recalculateTotal() {
let pstToPay = subtotal * pst;
pstToPay = parseFloat(pstToPay.toFixed(2));
let gstToPay = subtotal * gst;
gstToPay = parseFloat(gstToPay.toFixed(2));
let total = subtotal +pstToPay + gstToPay;
document.getElementById("subtotal").value = subtotal.toFixed(2).replace(/0+$/, "") ;
document.getElementById("pstToPay").value = pstToPay.toFixed(2);
document.getElementById("gstToPay").value = gstToPay.toFixed(2);
document.getElementById("total").value = total.toFixed(2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pizza Order Form</title>
<link rel="stylesheet" href="css/style.css">
<script src="scripts/script.js"></script>
<body>
<header>
<img src="media/pizza-served.jpg" width="600" height="277" alt="Pizza Logo"/>
<h1>Pizza Order Form</h1>
</header>
<form id="myForm" name="myForm" method="post" action="http://lavalamp.dyndns.org/~mult114/pizzaorder_olympic.php" onsubmit="return validateForm();" target="_blank">
<input type="hidden" name="difficulty" value="1" />
<fieldset id="contactinfo">
<legend style="font-size: larger;"><strong>Contact Information</strong></legend>
<label for="firstnameinput">First Name</label>
<input type="text" id="firstnameinput" name="FirstName_tf" /><br>
<label for="lastnameinput">Last Name</label>
<input type="text" id="lastnameinput" name="LastName_tf" /><br>
<label for="addrinput">Address</label>
<input type="text" id="addrinput" name="Address_tf" /><br>
<label for="phoneinput">Phone</label>
<input type="text" id="phoneinput" name="Phone_tf" /><br>
<label for="emailinput">Email Address</label>
<input type="email" id="emailinput" name="Email_tf" />
</fieldset>
<fieldset id="orderinfo">
<legend style="font-size: larger;"><strong>Order</strong></legend>
<fieldset id="pizzasize">
<legend>Pizza Size</legend>
<input type="radio" id="smallsize" name="Size_rg" value="10" onclick="calculateSize(this);">
<label for="smallsize">Small 10"</label><br>
<input type="radio" id="mediumsize" name="Size_rg" value="12" onclick="calculateSize(this);">
<label for="mediumsize">Medium 12"</label><br>
<input type="radio" id="largesize" name="Size_rg" value="15" onclick="calculateSize(this);">
<label for="largesize">Large 15"</label>
</fieldset>
<fieldset id="toppingbox">
<legend>Topping(s)</legend>
<input type="checkbox" id="anchovies" name="Anchovies_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="anchovies">Anchovies</label><br>
<input type="checkbox" id="doublecheese" name="DoubleCheese_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="doublecheese">Double Cheese</label><br>
<input type="checkbox" id="pepperoni" name="Pepperoni_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="pepperoni">Pepperoni</label><br>
<input type="checkbox" id="mushrooms" name="Mushroom_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="mushrooms">Mushrooms</label><br>
</fieldset>
<fieldset id="instructions">
<legend>Special Instructions</legend>
<textarea id="textarea" name="instructions" rows="5" cols="50" placeholder="Enter your message here!(special requests, delivery details, etc.)"></textarea>
</fieldset>
</fieldset>
<fieldset id="payments">
<legend style="font-size: larger;"><strong>Payment</strong></legend>
<label>Select Payment Method:</label>
<select id="paymethods" name="Payment_menu" required="required">
<option value="select">- Select One -</option>
<option value="cash">Cash</option>
<option value="debit">Debit</option>
<option value="credit">Credit Card</option>
</select>
</fieldset>
<fieldset id="calcprice">
<legend style="font-size: larger;"><strong>Order Total</strong></legend>
<label for="subtotal">SubTotal $:</label>
<input type="text" id="subtotal" name="SubTotal_tb" readonly><br>
<label for="pstToPay">PST $:</label>
<input type="text" id="pstToPay" name="PST_tb" readonly><br>
<label for="gstToPay">GST $:</label>
<input type="text" id="gstToPay" name="GST_tb" readonly><br>
<label for="total">Total $:</label>
<input type="text" id="total" name="Total_tb" readonly><br>
</fieldset>
<input type="submit" name="Submit_but">
</form>
</body>
</html>
You can use math.round() function available in js to round your values.
For example say your total value can be rounded of by providing math.round() func to it.
let total = math.round(subtotal + pstToPay + gstToPay);
Reference page:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

jquery on form calculation max values without submit

how can i do dynamic form calculation without submit? submitting is about php server. I need to calculate this form with limiting max values. Example result value can't be above buy value. when above must give error submit button disabled.
I can't find any solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#storage","#result","#account").on(keyup, change(function(){
var abc = $("#abc").val();
var price = $("#price").val();
var storage = $("#capacity").val() - $("#abc").val();
$("#storage").val(storage);
var result = $("#price").val() * $("#abc").val();
$("#result").val(result);
var account = buy - result;
$("#account").val(account);
});
});
</script>
</head>
<body>
<form method="post" action="" >
<input id="buy" type="hidden" class="form-control" name="buy" value="5000000" />
<input type="hidden" id="capacity" class="form-control" name="capacity" value="1000000" />
Storage : <input id="storage" type="text" class="form-control" name="storage" min="0" max="1000000" value=""/><br>
Abc: <input id="abc" type="text" class="form-control" name="abc" min="0" max="1000000" value="" /> <br>
Price: <input id="price" type="text" class="form-control" name="price" value="15" /> <br>
Result: <input id="result" type="text" class="form-control" name="result" value=""/> <br>
Account: <input id="account" type="text" class="form-control" name="account" max="5000000" value="" /> <br>
<input type="button" id="submit" value="submit">
</form>
</body>
</html>
Use an input / keyup event listener. For example (Vanilla JS):
document.getElementById('myInput').addEventListener("keyup", function() {
console.log(document.getElementById("myInput").value);
// Do your stuff here
});
<input id="myInput" />
Or with jQuery:
$('#myInput').keyup(function() {
console.log($("#myInput").val());
// Do your stuff here
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
Although this is heplful, JavaScript (besides Node) is client-side and can be easily overriden, so make sure you evaluate the input in the backend too.

How to make submit button work and showing the results in another page with only using javascript?

<!DOCTYPE html>
<html>
<head>
<title>Sign-up form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<main>
<form class="center" action="submit.htm" method="post">
<h2>Enter information here</h2>
<div class="form-item">
<label class="category" for="firstname">First name</label>
<input type="text" name="firstname" id="firstname">
</div>
<div class="form-item">
<label class="category" for="lastname">Last name</label>
<input type="text" name="lastname" id="lastname">
</div>
<div class="form-item">
<label class="category" for="meal">With Meal?</label>
<input type="radio" name="meal" value="no" id="no" checked>
<label class="value" for="no">NO</label>
<input type="radio" name="meal" value="yes" id="yes">
<label class="value" for="yes">YES</label>
</div>
<div class="form-item">
<label class="category" for="email">Email</label>
<input type="email" name="email" id="email">
</div>
<div class="form-item">
<label class="category" for="number">Contact number</label>
<input type="number" name="number" id="number">
</div>
<button type="submit">Submit</button>
</form>
</main>
</body>
</html>
I want to show the output of whatever the user input in a different page after clicking submit. how can i do this without using php and only javascript? JS is very hard for me to nderstand so pls help :(
If you use POST method you have to use any server side language like PHP. If you want to achieve the same thing in JavaScript it is very easy. Change the method to get.
<form class="center" action="submit.htm" method="get">
You can write your submit.htm like this.
<div id='firstname'></div>
<div id='lastname'></div>
<div id='meal'></div>
<div id='email'></div>
<div id='number'></div>
Your JavaScript code goes here.
var data = getJsonFromUrl();
document.getElementById("firstname").innerHTML = data['firstname'];
document.getElementById("lastname").innerHTML = data['lastname'];
document.getElementById("meal").innerHTML = data['meal'];
document.getElementById("email").innerHTML = data['email'];
document.getElementById("number").innerHTML = data['number'];
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}

Keyup function isn't changing input box?

I am trying to create a simple form that calculates a few fields and calculates the total price as unit cost * quantity. I am trying to use a keyup function to automatically change the unit price as the entered unit price changes, but when I change the price nothing happens.
HTML
<!-- Div for quantity -->
<div class="form-group">
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<!-- Div for unit price -->
<div class="form-group">
<input type="number" class="form-control" id="unitPrice" name="unitPrice" placeholder="Unit Price" required>
</div>
<!-- div for cost -->
<div class="form-group">
<input type="number" class="form-control" id="cost" name="cost" placeholder="Cost" required>
</div>
JS
$(document).ready(function () {
$("#unitPrice").keyup(function () {
var quantity = +$("#quantity").val();
var price = +$("#unitPrice").val();
$("#cost").val(quantity * unitPrice);
});
});
});
It's a typo.
Change
$("#cost").val(quantity * unitPrice);
to
$("#cost").val(quantity * price);
Here's a working solution. Your variable name is
price
NOT unitPrice
.Hope it helps!
$(document).ready(function () {
$("#unitPrice").keyup(function () {
var quantity = +$("#quantity").val();
var price = +$("#unitPrice").val();
$("#cost").val(quantity * price);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="form-group">
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<!-- Div for unit price -->
<div class="form-group">
<input type="number" class="form-control" id="unitPrice" name="unitPrice" placeholder="Unit Price" required>
</div>
<!-- div for cost -->
<div class="form-group">
<input type="number" class="form-control" id="cost" name="cost" placeholder="Cost" required>
</div>
You have used the wrong variable name. Replace this line
$("#cost").val(quantity * unitPrice);
with
$("#cost").val(quantity * price);

Wont log to console, javascript

I am having trouble writing to the console with the following code. Unsure as to why it is not working as am a beginner JavaScript programmer. May be a stupid question because I am new to JavaScript.
Javascript:
function process(){
'use strict';
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("pass").value;
var age = document.getElementById("age").value;
console.log(user);
};
function init(){
'use strict';
document.getElementById('signUp').onsubmit = process;
};
window.onload = init;
html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Employee Register</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
</head>
<body>
<form action="#" method="post" id="signUp" class="form">
<h1>Sign up.
<span>Please complete all information.</span>
</h1>
<label for="user">
<span>Username:</span>
<input type="text" name="user" id="user" required>
</label>
<label for="name">
<span>Full Name:</span>
<input type="text" name="name" id="name" required>
</label>
<label for="email">
<span>Email Address:</span>
<input type="email" name="email" id="email" required>
</label>
<label for="pass">
<span>Password:</span>
<input type="password" name="pass" id="pass" required>
</label>
<label for="age">
<span>Age:</span>
<input type="text" name="age" id="age" required>
</label>
<input type="submit" value="Submit" id="submit">
</form>
<div id="members" class="output">
<h1>Registered Members</h1>
</div>
<script src="register.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
The reason for this is that the log is renewed for every request (in case of Chrome browser) and as you are setting the console.log to be fired onsubmit the log is logged but will be cleared immediately
Check the checkbox Preserve Log in the console of Chrome.
You can change the input type to a normal button to prevent the submit <input type="button" value="Submit" id="submit">.
After doing whatever you want with the fields you can submit the form with signUp.submit() or document.getElementById('signUp').submit().

Categories