Uncaught ReferenceError: function is not defined. Onclick/ onChange - javascript

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>

Related

Calculate percentage function

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;
}

Using Radio Button Values in Javascript

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>

How can I add up my selection lists, radios, and checkboxes to total?

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

add additional value to the total

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>

Put name attribute of all checked checkboxes into array - JavaScript

I have a pizza ordering form that contains checkboxes for toppings. Each new Pizza is an object that is placed into an array. One of the variables inside the pizza object is toppings. I would like the toppingsvariable to contain an array of all the checkboxes name attribute. How do I do that?
I have made an attempt, but it doesn't seem to work:
HTML:
<fieldset>
<form class="pure-form">
<legend>
<center><label><b>Name: </b></label>
<select class="nameSelection" name="nameSelectionPizza">
<option value="0">Please Select:</option>
</select></center>
</legend>
<br>
<label><b>Pizza Type: </b></label>
<select class="pizza" name="firstMenu" disabled>
<option data-price="0">Please Select:</option>
<option name="margarita">Margarita</option>
<option name="deep-pan">Deep Pan</option>
<option name="stuffed-crust">Stuffed Crust</option>
</select>
<span style="float:right">
<label><b>Pizza Size: </b></label>
<select class="pizzaSize" disabled>
<option data-price="0">Please Select:</option>
<option name="e-small" data-price="4.99">Extra Small - £4.99</option>
<option name="small" data-price="5.99">Small - £5.99</option>
<option name="medium" data-price="6.99">Medium - £6.99</option>
<option name="large" data-price="8.99">Large - £8.99</option>
<option name="e-large" data-price="9.99">Extra Large - £9.99</option>
<option name="f-size" data-price="10.99">Family Size - £10.99</option>
</select>
</span>
</form>
</fieldset>
<fieldset style = "border-top:0px">
<form class="pure-form">
<legend><b>Toppings (99p Each): </b></legend>
<input type="checkbox" class="toppings" name="onions" disabled>Onions</input>
<input type="checkbox" class="toppings" name="mushrooms" disabled>Mushrooms</input>
<input type="checkbox" class="toppings" name="peppers" disabled>Peppers</input>
<input type="checkbox" class="toppings" name="olives" disabled>Olives</input>
<input type="checkbox" class="toppings" name="garlic" disabled> Garlic</input>
<input type="checkbox" class="toppings" name="peperoni" disabled>Peperoni</input>
<input type="checkbox" class="toppings" name="cheese" disabled>Pesto</input>
</form>
</fieldset>
JS:
var pizzaArray = new Array();
function pizza(number, pizzaCost, toppingCost, name, pizzaType, pizzaSize, toppings) {
this.pizzaNumber = number;
this.pizzaCost = pizzaCost;
this.toppingCost = toppingCost;
this.name = name;
this.type = pizzaType;
this.size = pizzaSize;
this.toppings = toppings;
}
var pizzaCounter = 1;
pizzaArray.push(new pizza(pizzaCounter, 0.00, 0.00, "", "", "", ""));
$(document).on("change","input[type='checkbox']", function() {
var topArray = $(":checkbox:checked").next('name').map(function(){
return $(this).attr('name');
}).get();
var checked = $(this).parent().find(":checkbox:checked").length;
var toppingCost = (0.99 * checked);
var form = $(this).closest('div').attr("id");
var formID = form.replace( /^\D+/g, '');
for(var i = 0; i < pizzaArray.length; i++) {
if (pizzaArray[i].pizzaNumber == formID) {
pizzaArray[i].toppingCost = toppingCost;
pizzaArray[i].toppings = topArray;
alert((pizzaArray[i].toppings).toString());
calculateCost();
}
}
});
The error is in your use of next('name'). Remove that and your code should work fine:
var topArray = $(".toppings:checked").map(function(){
return this.name;
}).get();
Note that I changed the selector to use the class of the checkboxes to save any issues if you add further checkboxes to the page in future. I also used the name property directly from the DOMElement to save creating a needless jQuery object.

Categories