Struggling to get the desired results, code to test
The first two functions work, but the third one for the discount does not.
Depending on the number I put in the input field it should apply a discount up to 20% max on increments of 5,(so 1 = 5%, 2 = 10%, etc). No matter the value I put in the input field (deadline) value is stuck in applying the 20% discount. Full bit for testing:
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.querySelector("#servicePrice");
if (service_prices[selectedOption.value]) {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBoxes = form.querySelectorAll("#selectedBox");
selectedBoxes.forEach((box) => {
if (box.checked == true) {
extraPrices += 400;
}
});
return extraPrices;
}
//discount calc
const getDiscountPercent = (months) => (months < 4 ? months * 0.05 : 0.2);
const getTotal = (servicePrice, extraPrice, months) => {
const disTotal = servicePrice + extraPrice;
const discountPercent = getDiscountPercent(months);
return disTotal - disTotal * discountPercent;
};
//total final calc//
function Total() {
var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent();
document.getElementById("result").value = "€" + finalPrice;
}
<form action="" id="formulario" name="formulario">
<p> Type of Service
</p>
<select name="serviço" id="servicePrice" onchange="Total()">
<option value="none">Select a service
</option>
<option value="1500">1500€
</option>
<option value="4000">4000€
</option>
<option value="8000">8000€
</option>
</select>
<br>
<p>Deadline (months)
</p>
<input type="number" class="InStyle" id="months" name="months" onkeydown="Total()">
<br>
<!--checkbox-->
<h1>DESIRED EXTRAS
</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="Total()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="Total()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="Total()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="Total()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="Total()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="Total()"> News
<br>
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="Total()"> Social Network
<br>
<br>
<br>
<!--result-->
<h1>Estimated Total
</h1>
<input type="text" class="InStyle" disabled id="result">
</form>
You are not passing the months amount to getDiscountPercent function, neither taking months value from the input and also I advice you to use onChange event on month input .
function Total() {
var months = parseInt(document.querySelector('#months').value);
var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent(months);
document.getElementById("result").value = "€" + finalPrice;
}
Related
TL;DR
getTotal should give me a total of these 2 functions summed together but it's throwing me an error instead:
Uncaught ReferenceError: getTotal is not defined
onchange http://127.0.0.1:3211/XyZPage/Untitled-1.html:1
Uncaught ReferenceError: getTotal is not defined
onclick http://127.0.0.1:3211/XyZPage/Untitled-1.html:1
code:
var service_prices= new Array();
service_prices=["0"]= 0;
service_prices=["1500"]= 1500;
service_prices=["4000"]= 4000;
service_prices=["8000"]= 8000;
function getServicePrice(){
var serviceOptionPrice=0;
var form = document.forms["formulario"];
var selectedOption = form.elements["servicePrice"];
serviceOptionPrice = service_prices[selectedOption.value];
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices(){
var extraPrices=0;
var form=document.forms["formulario"];
var selectedBox = form.elements["selectedBox"];
if(selectedBox.checked==true){
extraPrices=400;
}
return extraPrices;
}
//total final calc//
function getTotal(){
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").innerHTML= "eddies" + finalPrice;
}
I've tried couple fixes from threads here but nothing worked so far. JS alongside html https://jsfiddle.net/j1t68npf/
You have a several syntax errors in your JS which prevent the parser from reaching the getTotal() definition. So it remains undefined.
The offending sections is:
service_prices=["0"]= 0;
service_prices=["1500"]= 1500;
service_prices=["4000"]= 4000;
service_prices=["8000"]= 8000;
If you repair this you will no longer get the undefined error.
After this is fixed there are several other coding errors which, when resolved will get you this:
//reference the form by it's ID//
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.querySelector("#servicePrice");
if (service_prices[selectedOption.value]) {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBoxes = form.querySelectorAll("#selectedBox");
selectedBoxes.forEach(box => {
if (box.checked == true) {
extraPrices += 400;
}
})
return extraPrices;
}
//total final calc//
function getTotal() {
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").value = "eddies" + finalPrice;
}
<form id="formulario">
<p> Type of Service</p>
<select name="serviço" id="servicePrice" onchange="getTotal()">
<option value="none">Select a service</option>
<option value="1500">1500€</option>
<option value="4000">4000€</option>
<option value="8000">8000€</option>
</select>
<!--checkbox-->
<h1>DESIRED EXTRAS</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="getTotal()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="getTotal()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="getTotal()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="getTotal()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="getTotal()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="getTotal()"> News
<br>
<input type="checkbox" name="selectedBox"> Social Network
<br> <br> <br>
<!--result-->
<h1>Estimated Total</h1>
<input type="text" class="InStyle" disabled id="result">
</form>
It bears mentioning that you should not re-use ID values in html, they are supposed to be unique.
This is a corrected version of your code, as stated in comments there were multiple syntax errors, but most importantly, you're handling the checkbox collection as if it were a single checkbox.
In this version I iterate all checkboxes and accumulate 400 for each checked one.
//reference the form by it's ID//
//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;
function getServicePrice() {
var serviceOptionPrice = 0;
var form = document.forms["formulario"];
var selectedOption = form.elements["servicePrice"];
if (selectedOption.value != "none") {
serviceOptionPrice = service_prices[selectedOption.value];
}
return serviceOptionPrice;
}
//checkbox calculation//
function extraPrices() {
var extraPrices = 0;
var form = document.forms["formulario"];
var selectedBox = form.elements["selectedBox"];
selectedBox.forEach(el => {
if (el.checked) {
extraPrices += 400;
}
})
return extraPrices;
}
//total final calc//
function getTotal() {
var finalPrice = getServicePrice() + extraPrices();
document.getElementById("result").value = "eddies" + finalPrice;
}
<form id="formulario" name="formulario">
<p> Type of Service</p>
<select name="serviço" id="servicePrice" onchange="getTotal()">
<option value="none">Select a service</option>
<option value="1500">1500€</option>
<option value="4000">4000€</option>
<option value="8000">8000€</option>
</select>
<!--checkbox-->
<h1>DESIRED EXTRAS</h1>
<br>
<input type="checkbox" name="selectedBox" value="4" id="selectedBox" onclick="getTotal()"> Who we are
<input type="checkbox" name="selectedBox" value="5" id="selectedBox" onclick="getTotal()"> Where we are
<br>
<input type="checkbox" name="selectedBox" value="6" id="selectedBox" onclick="getTotal()"> Gun Gallery
<input type="checkbox" name="selectedBox" value="7" id="selectedBox" onclick="getTotal()"> eCommerce
<br>
<input type="checkbox" name="selectedBox" value="8" id="selectedBox" onclick="getTotal()"> Internal Mangement
<input type="checkbox" name="selectedBox" value="9" id="selectedBox" onclick="getTotal()"> News
<br>
<input type="checkbox" name="selectedBox"> Social Network
<br> <br> <br>
<!--result-->
<h1>Estimated Total</h1>
<input type="text" class="InStyle" disabled id="result">
</form>
Following on from my previous question, I am now struggling to pass the values of my radio buttons to my JavaScript function.
The desired output is to have both a 'BMR' value, and a 'recommended caloric intake' value, which is simply BMR x activity multiplier.
Here is both my JavaScript and HTML:
JavaScript
<script>
function calcCals() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let activity = document.getElementById("activity").value;
let calories;
let BMR;
// Calculate BMR
if (gender == 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
// Calculate Calories
if (activity == '1') {
calories = BMR * 1.2
} if (activity == '2') {
calories = BMR * 1.375
} if (activity == '3') {
calories = BMR * 1.55
} if activity == '4' {
calories = BMR * 1.725
} if activity == '5' {
calories = BMR * 1.9
}
console.log(BMR);
document.getElementById("bmrOutput").textContent = "Your BMR is " + BMR;
document.getElementById("calorieNeedsOutput").textContent = "Your Caloric Needs are " + calories;
event.preventDefault();
return;
}
</script>
HTML
<!--Enter Age and Gender-->
<h4>Age & Gender</h4>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="range" id="age" name="amountRange" min="16" max="80" value="30" oninput="this.form.amountInput.value=this.value">
<input type="number" id="age" name="amountInput" min="16" max="80" value="30" oninput="this.form.amountRange.value=this.value">
<!--Enter Height and Weight-->
<h4>Your Measurements</h4>
<input type="number" id="weight" placeholder="Weight in KG" required>
<input type="number" id="height" placeholder="Height in CM" required>
<!--Enter Activity Levels-->
<h4>Your Activity Level</h4>
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<!--Enter Goal and Contact Info-->
<h4>Your Goal + Contact Info</h4>
<input type="text" placeholder="What is your name?">
<input type="email" placeholder="Where shall we send your results?">
<select name="goal" id="goal">
<option value="lose">Lose Weight</option>
<option value="gain">Gain Muscle</option>
<option value="maintain">Maintain</option>
</select>
<!--Submit Button-->
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="bmrOutput"></p>
<p id="calorieNeedsOutput"></p>
</section>
In this solution I simplified the source code to read the radio button. When the submit button is clicked, the value of the selected radio button item is printed to the console. You can improve its algorithm by reading the value of the selected radio button element using the following approach.
let submitButton = document.getElementById('submitBtn');
submitButton.addEventListener('click', function() {
/* The value of the selected radio button element whose "name" attribute is "activity" from the <input> elements is assigned to the "activity" variable. */
let activity = document.querySelector('input[name="activity"]:checked').value;
console.log(`Activity: ${activity}`);
});
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<!--Submit Button-->
<button type="submit" id="submitBtn">Do Magic!</button>
The code snippet below shows the above solution applied to your code. For testing purposes, I removed the <form> element so that it would not submit after the button was clicked, and I made the click event fire for the button.
let submitButton = document.getElementById('submitBtn');
let firstAgeInput = document.getElementById('age1');
let secondAgeInput = document.getElementById('age2');
let gender = document.getElementById("gender");
let weightKG = document.getElementById("weight");
let heightCM = document.getElementById("height");
let age = document.getElementById('age1').value;
let bmrOutput = document.getElementById("bmrOutput");
let calorieNeedsOutput = document.getElementById("calorieNeedsOutput");
let ageInputs = document.querySelectorAll('.ageInputs');
/* Fields that may be null or empty should be checked for the calculation. */
function isValid() {
let activity = document.querySelector('input[name="activity"]:checked');
if(activity != null && weightKG.value.length != 0 && heightCM.value.length != 0)
return true;
return false;
}
/* This method updates the age value bidirectionally. */
function updateAge(newValue) {
secondAgeInput.value = newValue;
firstAgeInput.value = newValue;
}
/* Elements with the ".ageInputs" class style apply an input event. */
ageInputs.forEach(function(item, index) {
item.addEventListener('input', function() {
updateAge(this.value);
});
});
/* When the Submit button is clicked, this event is triggered and the result is printed to the HTML document. */
submitButton.addEventListener('click', function() {
if(isValid()) {
let activity = document.querySelector('input[name="activity"]:checked');
const bmrConstant = [1.2, 1.375, 1.55, 1.725, 1.9];
let calories, BMR = 10 * weightKG.value + 6.25 * heightCM.value - 5 * age;
(gender.value === 'male') ? (BMR += 5) : (BMR -= 161);
calories = BMR * bmrConstant[parseInt(activity.value) - 1];
bmrOutput.textContent = "Your BMR is " + BMR;
calorieNeedsOutput.textContent = "Your Caloric Needs are " + calories;
}
else
console.log("Fill in the blank fields in the form.");
});
<h4>Age & Gender</h4>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<!-- Items with the same id should not be used; therefore the following two items have been edited. -->
<input class="ageInputs" type="range" id="age1" name="amountRange" min="16" max="80" value="30">
<input class="ageInputs" type="number" id="age2" name="amountInput" min="16" max="80" value="30">
<h4>Your Measurements</h4>
<input type="number" id="weight" placeholder="Weight in KG" required>
<input type="number" id="height" placeholder="Height in CM" required>
<h4>Your Activity Level</h4>
<fieldset class="activity-select" id="activity">
<label><input type="radio" value="1" name="activity">Sedentary</label>
<label><input type="radio" value="2" name="activity">Lightly Active</label>
<label><input type="radio" value="3" name="activity">Moderately Active</label>
<label><input type="radio" value="4" name="activity">Very Active</label>
<label><input type="radio" value="5" name="activity">Extremeley Active</label>
</fieldset>
<h4>Your Goal + Contact Info</h4>
<input type="text" placeholder="What is your name?">
<input type="email" placeholder="Where shall we send your results?">
<select name="goal" id="goal">
<option value="lose">Lose Weight</option>
<option value="gain">Gain Muscle</option>
<option value="maintain">Maintain</option>
</select>
<button id="submitBtn">Do Magic!</button>
<p id="bmrOutput"></p>
<p id="calorieNeedsOutput"></p>
I have created a test website to learn some js by making an online store than basically has values in a form
what i am stuck on is when my html calls the function on shipping
its not adding the shipping properly (only for ground which seems to be defaulted to)
I need the ability for the script to calculate the proper shipping charge depending on radio button selected
function calcTaxes() {
cost = 10;
var taxed = cost * document.getElementById("qty").value;
var freight = document.getElementById("shipping").value;
var freightNum = parseInt(freight, 10);
var totalCost;
if (taxed < 10){
taxed = (taxed * .1) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
else if (taxed > 10 && taxed < 20){
taxed = (taxed * .0725) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
else {
taxed = (taxed * .05) + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" +totalCost;
}
}
<h2>Order Form -- T-shirts $10 each</h2>
<br>
<form>
Name: <input type="text" placeholder="Your name here" ><br><br>
Address: <textarea placeholder="Your Address"></textarea><br><br>
Email: <input type="email" placeholder="Your email address" ><br><br>
<label for="size">Choose a size: (Same Price) </label>
<select id="size" name="size">
<option value="XS">XS -Extra Small</option>
<option value="S">S-Small</option>
<option value="M">M-Medium</option>
<option value="L">L-Large</option>
<option value="XL">XL-Extra Large</option>
<option value="XXL">XXL-Extra Extra Large</option>
</select><br><br>
Color: <input type="radio" value="Black" name="color">Black
<input type="radio" value="White" name="color">White
<input type="radio" value="Gun-Metal" name="color">Gun-Metal
<br><br>
Quantity: <input id="qty" type="number"><br><br>
Shipping: <input type="radio" value= "10" id="shipping" name="shipp">Ground ($10)
<input type="radio" value="20" id="shipping" name="shipp" >Overnight ($20)
<input type="radio" value="25" id="shipping" name="shipp" >Drone-Drop ($25)
<br><br>
<br>
</form>
<button class="taxes" onclick="calcTaxes()">Calculate Total</button><br>
Includes shipping and taxes:<p id="tax"></p>
</body>
</html>
The problem is that you are using document.getElementById which will always return the first element with I'd shipping.
Try using document.getElementsByName
Remember it'll return an array of elements
You'll need to get the value from the current selected radio button, for example, you could do:
var freight = document.querySelector('input[name="shipp"]:checked').value;
function calcTaxes() {
cost = 10;
var taxed = cost * document.getElementById("qty").value;
var freight = document.querySelector(`input[name="shipp"]:checked`)
.value;
var freightNum = parseInt(freight, 10);
var totalCost;
if (taxed < 10) {
taxed = taxed * 0.1 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
} else if (taxed > 10 && taxed < 20) {
taxed = taxed * 0.0725 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
} else {
taxed = taxed * 0.05 + taxed;
totalCost = taxed + freightNum;
document.getElementById("tax").innerHTML = "$" + totalCost;
}
}
<h2>Order Form -- T-shirts $10 each</h2>
<br />
<form>
Name: <input type="text" placeholder="Your name here" /><br /><br /> Address: <textarea placeholder="Your Address"></textarea><br /><br /> Email: <input type="email" placeholder="Your email address" /><br /><br />
<label for="size">Choose a size: (Same Price) </label>
<select id="size" name="size">
<option value="XS">XS -Extra Small</option>
<option value="S">S-Small</option>
<option value="M">M-Medium</option>
<option value="L">L-Large</option>
<option value="XL">XL-Extra Large</option>
<option value="XXL">XXL-Extra Extra Large</option>
</select><br /><br /> Color: <input type="radio" value="Black" name="color" />Black
<input type="radio" value="White" name="color" />White
<input type="radio" value="Gun-Metal" name="color" />Gun-Metal
<br /><br /> Quantity: <input id="qty" type="number" /><br /><br /> Shipping:
<input type="radio" value="10" id="shipping" name="shipp" />Ground ($10)
<input type="radio" value="20" id="shipping" name="shipp" />Overnight ($20)
<input type="radio" value="25" id="shipping" name="shipp" />Drone-Drop ($25) <br /><br />
<br />
</form>
<button class="taxes" onclick="calcTaxes()">Calculate Total</button><br /> Includes shipping and taxes:
<p id="tax"></p>
So what I can see the freight value is being assigned the first value since it's calling the first id with the name shipping with document.getElementById('shipping').
You could assign each radio button with an onclick="myShippingCost(this.value)" and in your JS, call that function if your main calcTaxes().
Example:
var radioValue;
myShippingCost(value) {
radioValue = value;
}
calcTaxes() {
// ...your code
var freight = radioValue;
// ...your code
}
I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById
I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>