get random objects from a separate file - javascript

I am trying to create a random name generator which takes its first and last names from separate files.
Which is the easiest way to do so while keeping the resource files easily modifiable?
Thanks for your help!
Edit:
//---------------------first js-file humanVillages.js
var nameSyllables = ["aber", "ac", "acc", "ock", "afon", "avon", "ar", "ard"];
function CreateNewHumanName()
{
//Creates a first name with 1-3 syllables
var firstName = "";
var numberOfSyllablesInFirstName = Math.floor(getRandom(2, 5));
for (var i = 0; i < numberOfSyllablesInFirstName; i++)
{
firstName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))];
}
var firstNameLetter = firstName[0];
firstName = firstName.slice(1);
firstNameLetter = firstNameLetter.toUpperCase();
firstName = firstNameLetter + firstName;
//Creates a second name with 2-4 syllables
var secondName = "";
var numberOfSyllablesInSecondName = Math.floor(getRandom(4, 6));
for (var i = 0; i < numberOfSyllablesInSecondName; i++)
{
secondName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))];
}
var secondNameLetter = secondName[0];
secondName = secondName.slice(1);
secondNameLetter = secondNameLetter.toUpperCase();
secondName = secondNameLetter + secondName;
// var completeName = firstName + " " + secondName;
var completeName = firstName;
return completeName;
}
//-------------second js file scripts.js
// Declare the Object of Village, with name,
// number of villagers and array of villager objects
function Village(villageName, villagersAmount, villagersList, villageSizeDescriptor) {
this.villageName = villageName;
this.villagersAmount = villagersAmount;
this.villagersList = villagersList;
this.villageSizeDescriptor = villageSizeDescriptor;
};
Village.prototype.villageName = function() {
return this.villageName;
};
Village.prototype.villagersAmount = function() {
return this.villagersAmount;
};
Village.prototype.villagersList = function() {
return this.villagersList;
};
Village.prototype.villageSize = function() {
return this.villageSize;
};
console.log("Village created correctly");
// Declare the Object of Villager, with preset first_name,
function Villager(firstName) {
this.firstName = firstName;
};
Villager.prototype.firstName = function() {
return this.firstName;
};
console.log("Villager created correctly");
// Random Number Generator for incremental village size choices
function getRandom(min, max) {
return Math.random() * (max - min) + min;
};
$(document).ready(function() {
$("form#create_village").submit(function(event) {
event.preventDefault();
// Gather input for Village Creation
var villageSizeInput = parseInt($("#size").val());
var villagersAmount = 0;
var villageSizeDescriptor = "";
// Use manual input for amount of villagers if selected and input is given
// Otherwise take villageSizeInput to switch to right random number range
if (villageSizeInput == 0 && $("input#amount").val() == "") {
alert("Please enter a value if you choose manual input!")
} else if (villageSizeInput == 0 ) {
villagersAmount = parseInt($("input#amount").val());
} else if (villageSizeInput == 1){
villagersAmount = Math.floor(getRandom(0, 50000));
} else {
switch (villageSizeInput) {
case 2:
villagersAmount = Math.floor(getRandom(0, 100));
break;
case 3:
villagersAmount = Math.floor(getRandom(100, 500));
break;
case 4:
villagersAmount = Math.floor(getRandom(500, 1000));
break;
case 5:
villagersAmount = Math.floor(getRandom(1000, 2000));
break;
case 6:
villagersAmount = Math.floor(getRandom(1000, 5000));
break;
case 7:
villagersAmount = Math.floor(getRandom(5000, 10000));
break;
case 8:
villagersAmount = Math.floor(getRandom(10000, 25000));
break;
case 9:
villagersAmount = Math.floor(getRandom(25000, 50000));
break;
}
}
// Take villagersAmount to set corresponding verbal size descriptor
if (villagersAmount < 100) {
villageSizeDescriptor = "Thorp";
} else if (villagersAmount < 500) {
villageSizeDescriptor = "Hamlet";
}else if (villagersAmount < 1000) {
villageSizeDescriptor = "Village";
}else if (villagersAmount < 2000) {
villageSizeDescriptor = "Small Town";
}else if (villagersAmount < 5000) {
villageSizeDescriptor = "Large Town";
}else if (villagersAmount < 10000) {
villageSizeDescriptor = "Small City";
}else if (villagersAmount < 25000) {
villageSizeDescriptor = "Large City";
}else {
villageSizeDescriptor = "Metropolis";
}
//create instance of Village and Villager
//call on function in humanVillages.js to randomly create a villageName
var newVillageName = CreateNewHumanName();
var newVillage = new Village(newVillageName, villagersAmount, [], villageSizeDescriptor)
var newVillager = new Villager("Bob");
// Create output of Village
$("#villageType").text(newVillage.villageSizeDescriptor);
$("#villagersAmount").text(newVillage.villagersAmount);
$("#villageName").text(newVillage.newVillageName);
// Random creation of Villagers
for (var index = 0; index < villagersAmount; index += 1) {
newVillage.villagersList.push(newVillager.firstName);
$("ul#villagers_names").append("<li><span class='villager'>" + newVillager.firstName + "</span></li>");
}
// Reset manual Input Value
$("input#amount").val("");
});
});
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css" media="screen" title="no title" charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="js/scripts.js"></script>
<script src="resources/humanVillages.js"></script>
<title>Village Creator 1.0</title>
</head>
<body>
<div id="input">
<!-- Selecting input for the village creation -->
<h3>Create a village!</h3>
<form id="create_village" onsubmit="return false;">
<table>
<tbody>
<tr>
<td>Select a town size</td>
<td>
<select id="size">
<!-- Selecting town size by increment -->
<option value="0"selected="">Manual</option>
<option value="1">Any</option>
<option value="2">Thorp</option>
<option value="3">Hamlet</option>
<option value="4">Village</option>
<option value="5">Small Town</option>
<option value="6">Large Town</option>
<option value="7">Small City</option>
<option value="8">Large City</option>
<option value="9">Metropolis</option>
</select>
</td>
<td>
<!-- Selecting town size by specific numeric input -->
<label for="amount">The amount of villagers: </label>
<input type="number" name="amount" id="amount">
</td>
</tr>
<tr>
<td>Select a town name</td>
<td>
<select id="name">
<!-- Selecting town name by random racial name -->
<option value="0"selected="">Manual</option>
<option value="1">Random Drarven</option>
<option value="2">Random Elven</option>
<option value="3">Random Gnome</option>
<option value="4">Random Orc</option>
<option value="5">Random Halfling</option>
<option value="6">Random Human</option>
<option value="7">Random Other</option>
</select>
</td>
<td>
<!-- Selecting town name by specific spelled input -->
<label for="name">The name of the village: </label>
<input type="text" name="name" id="name">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-submit">Create!</button>
</form>
</div>
<div id="output">
<h3>Here there be a village!</h3>
<!-- Output of village parameters -->
<table>
<tr>
<th>Settlement Name</th>
<td><span id="villageName"></span></td>
</tr>
<tr>
<th>Settlement Type</th>
<td><span id="villageType"></span></td>
</tr><tr>
<th>Population</th>
<td><span id="villagersAmount"></span></td>
</tr>
<tr>
<th>Villager Names</th>
<td><ul id="villagers_names"></ul></td>
</tr>
</table>
</div>
</body>
</html>

Checkout the require() function in node, it helps you access objects and functions that maybe on separate files.
file1: nums.js
var obj = {
name: 'jack',
age: 30
};
module.exports = obj; //exports the object
file2: app.js
var nums = require('./nums');
console.log(nums); // prints --> { name: 'jack', age: 30 }
UPDATED:
file1: nums.js
var arr = [{
name: 'jack',
age: 30
}, {
name: 'a',
age:40
}, {
name: 'abc',
age:40
}];
module.exports = arr;
file2: app.js
var nums = require('./nums');
var rand = Math.floor(Math.random() * nums.length);
console.log(rand);
console.log(nums[rand]);

Related

Displaying two values from two different arrays

I need to display the highest test score out of one array and the person who received that score from another array. Here is the code so far:
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
}
}
var showBest = function() {
$("results").value = "";
$("results").value += "High Score = " + Math.max.apply(null, scores) + "\n";
$("results").value += "The highest scoring student is = " //here is where I need help
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
names[names.length] = $("name").value;
scores[scores.length] = parseInt($("score").value);
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
Is there any way to combine the arrays so they associate with each other? Even then I wouldn't know how to display the student separately from the score. Ideally hitting the "show_best" button would show the highest score and the name of the student who received that score.
Try this:
var showBest = function() {
const max = Math.max.apply(null, scores);
$("results").value = "";
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + names[scores.indexOf(max)] //here is where I need help
}
This is a solution using your data structure:
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
}
}
var showBest = function() {
$("results").value = "";
var max = Math.max.apply(null, scores);
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + names[scores.indexOf(max)];
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
names[names.length] = $("name").value;
scores[scores.length] = parseInt($("score").value);
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="test_scores.js"></script>
</head>
<body>
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
</body>
</html>
I would advice you, as suggested in the comment, to pass to an object structure in the form:
{
name: "example"
score: 10
}
var testResults = [
{
name: "Ben",
score: 88
},{
name: "Joel",
score: 98
},{
name: "Judy",
score: 77
},{
name: "Anne",
score: 88
}
];
var textDisplay;
var $ = function(id) {
return document.getElementById(id);
}
var listArray = function() {
$("results").value = "";
for (var i = 0; i < testResults.length; i++) {
$("results").value += testResults[i].name + ", " + testResults[i].score + "\n";
}
}
var showBest = function() {
$("results").value = "";
var scores = testResults.map(function(res) { return res.score;});
var max = Math.max.apply(null, scores)
var name = testResults.filter(function(res) { return res.score === max;}).pop().name;
;
$("results").value += "High Score = " + max + "\n";
$("results").value += "The highest scoring student is = " + name;
}
var addElement = function() {
$("results").value = "";
// get user entries
var name = $("name").value;
var score = parseInt($("score").value);
// check entries for validity
if (name == "" || isNaN(score) || score < 0 || score > 100) {
alert("You must enter a name and a valid score");
} else {
testResults.push({
name: $("name").value,
score: parseInt($("score").value)
});
$("name").value = "";
$("score").value = "";
}
$("name").focus();
}
window.onload = function() {
$("list_array").onclick = listArray;
$("add").onclick = addElement;
$("show_best").onclick = showBest;
$("name").focus();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="test_scores.js"></script>
</head>
<body>
<section>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array"><br>
<h2>Results</h2>
<textarea id="results"> </textarea><br>
<input type="button" id="list_array" value="List Array"><br>
<input type="button" id="show_best" value="Show Best Score"><br>
</section>
</body>
</html>
The following is an example of how to combine the two arrays and find the highest score student:
var scores = [
{name: "ben", score: 88},
{name: "Joel", score: 98},
{name: "Judy", score: 77},
{name: "Anne", score: 88}
];
var getHighScoreStudent = function(scores) {
return scores.reduce(function(acc, item) {
if (item.score > acc.score) {
return item;
} else {
return acc;
}
});
};
var ans = getHighScoreStudent(scores);
console.log(ans);

how to apply discount

I am building a ticket purchase system to get better in my javascript. I need help with some of my code. I can get the total of everything I want, but I am unable to get my discount function to work.
The total is calculated as (Show price * number of tickets) + (price of the delivery method)
when: the number of tickets > 6 the discount should be 10 per cent of the total.
when: the number of tickets > 10 the discount should be 15 per cent of the total.
the discount should be displayed separately to the total.
Dont mind some of the code that are comments as i used that as refrences.
This is the code:
java script:
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 6
if (seatstotal > x) {
(seatstotal > 10)
DiscountPrice = showtotal - (showtotal * .10)
}
else if
{
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}
html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="theatre tickets page for assignment">
<link rel="stylesheet" href="theatretickets.css">
<title>Theatre Tickets</title>
</head>
<body class="background">
<script src="theatretickets.js"></script>
<img class="logoimage" src="" alt="logo">
<h1 class="title">Theatre Tickets</h1>
<!--navigation -->
<nav>
<ul class="a">
<li class="hp">Fruit Machine</li>
<li class="hp">Theatre Tickets</li>
</ul><br><br>
</nav>
<!--forms-->
<!--name-->
<form name="bookform" id="bookform" class="fullform" method="post">
<h2>Name</h2>
<label for="fname">Full Name</label><br>
<input type="text" id="fname" name="fname" required=""><br>
<!--address-->
<h2>Address</h2>
<label for="noofaddress">Full Address</label><br>
<input type="text" id="noofaddress" name="noofaddress" required=""><br>
<!--shows-->
<h2>Currently Available Shows</h2>
<select name="shows" id="shows" onchange="getshowprice()">
<option value="79" selected class="Phantom" id="Phantom">Phantom Of The Opera</option>
<option value="85" class="hamilton" id="hamilton">Hamilton</option>
<option value="67" class="lionking" id="lionking">Lion King</option>
<option value="83" class="misssaigon" id="misssaigon">Miss Saigon</option>
</select><br>
<label id="display"></label>
<!--delivery-->
<h2>Method Of Delivery</h2>
<select id="delivery" name="delivery" onchange="getdeliveryprice()">
<option id="eticket" value="0" selected>E-Ticket</option>
<option id="boxoffice" value="1.50">Collect from Box Office</option>
<option id="posted" value="3.99">Posted</option>
</select><br>
<!--display the delivery cost label-->
<label id="displaydelivery"></label>
<!--seats-->
<h2>Number Of Seats</h2>
<input type="number" id="seats" name="seats" min="1" required=""
placeholder="Number of Seats"><br>
<label id="seatprice"></label><br><br>
<!--book button-->
<button type="button" name="book" id="book" onclick="gettotal()">Book</button><br><br>
<div id= "displaytotal"></div>
<div id="discount"></div>
<div id="finalcost"></div>
</form>
</body>
When no. of ticket is greater than 10, you are still applying 10%, so replace it with 15%, and I think you should first check condition for 10 and then condition for 6 in your if-else, see the new edited code. I don't know what is y here so can't comment on that.
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 10;
var DiscountPrice = 0;
if (seatstotal > x) {
DiscountPrice = showtotal - (showtotal * .15)
}
else if
(seatstotal > 6)
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}

How can I calculate the total value of amount due after choosing different option from drop-down list?

I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.

I want to display the price value for selected items using switch statement

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
addEvent(window, ‘load’, initialize);
function initialize()
{
// add an event to the drop down list
addEvent(document.getElementById(’chips’), ‘change’, getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
}
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
// lookup in the ‘table’ the cost associated with the product
function getPrice()
{
var chipName = this.options[this.selectedIndex].text;
var chipType = this.options[this.selectedIndex].value;
var outField = document.getElementById(’cost’);
master:
switch(chipType)
{
case "ICs":
for (var i = 0; i < ICs.length; i++)
{
if (ICs[i].name == chipName)
{
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++)
{
if (snacks[i].name == chipName)
{
outField.value = snacks[i].price;
break master;
}
}
}
break;
default:
outField.value = "Not Found";
}
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option>Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p>
</form>
</body>
</html>
// In the above code snippets I am trying to show the price for selected chip ,but no price is being shown in the input field.I have attached the output screen shot.I have built two arrays with a custom object ,simulating two database tables.
I am also defining one function getPrice for associating the price related to the product.
Thanks in advance
output screenshot
This works.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
window.onload = initialize;
function initialize()
{
document.getElementById('chips').addEventListener('change', getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
};
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
function getPrice()
{
var selectelem = document.getElementById("chips"), outField = document.getElementById('cost'), outvalue="";;
var chipName = selectelem.options[selectelem.selectedIndex].text;
var chipType = selectelem.value;
if(!chipType)
{
outField.value = ""; return;
}
switch(chipType)
{
case "ICs":
var arr = ICs.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
case "snacks":
var arr = snacks.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
default: outvalue = "Not Found"; break;
}
outField.value = outvalue;
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option value="signals">TCP</option>
<option value="computer">Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p> </form>
</body>
</html>
The switch is wrong. Should be something like this:
switch (chipType) {
case "ICs":
for (var i = 0; i < ICs.length; i++) {
if (ICs[i].name == chipName) {
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++) {
if (snacks[i].name == chipName) {
outField.value = snacks[i].price;
break master;
}
}
break;
default:
outField.value = "Not Found";
break;
}
Instead of AddEvent, you can use addEventListener. For example:
var chips = document.getElementById('chips');
chips.addEventListener('change', getPrice);

function not defined, but i'm quite sure i defined it.. What am i missing?

I'm trying to make a form using HTML & JavaScript.
I defined a lot of functions, but one of them is giving me some errors saying the functions aren't defined.. I'm quite sure though that i defined them.. Maybe i miss something somewhere or i defined them incorrectly? Not quite sure where the problem is!
The errors i'm getting are:
Uncaught ReferenceError: selectedBinding is not defined
Uncaught ReferenceError: selectedStaples is not defined
Uncaught ReferenceError: selectedHoles is not defined
Maybe you guys can check my code and look for the error i can't find?
var elems = {
staplesSelect: document.getElementById("makingStaples"),
holeSelect: document.getElementById("makingHoles"),
bindingSelect: document.getElementById("makingBinding"),
amountOfSetsResults: document.getElementById("amountOfSetsResults"),
amountOfPagesResults: document.getElementById("amountOfPagesResults"),
binding: document.getElementById("binding"),
stapling: document.getElementById("stapling"),
holes: document.getElementById("holes"),
paperWeight: document.getElementById("paperWeight"),
bindingResults: document.getElementById("bindingResults"),
holesResults: document.getElementById("holesResults"),
staplingResults: document.getElementById("staplingResults"),
totalAmountOfPagesResults: document.getElementById("totalAmountOfPagesResults"),
paperWeightResults: document.getElementById("paperWeightResults"),
bindingMethod: document.getElementById("bindingMethod"),
staplingMethod: document.getElementById("staplingMethod"),
holesMethod: document.getElementById("holesMethod"),
doubleSided: document.getElementById("doubleSided"),
pricePaperWeightResults: document.getElementById("pricePaperWeightResults"),
blackAndWhite: document.getElementById("blackAndWhite"),
colorResults: document.getElementById("colorResults"),
totalPricePrints: document.getElementById("totalPricePrints"),
totalPrice: document.getElementById("totalPrice"),
pricePerPageResults: document.getElementById("pricePerPageResults"),
calculation: document.getElementById("calculation"),
calculate: document.getElementById("calculate"),
amountOfSetsInput: document.getElementById("amountOfSetsInput"),
amountOfPagesInput: document.getElementById("amountOfPagesInput")
}
// Hiding calculations from page
toggleVisibility(elems.calculation, true);
// Defining the color prints pricelist
var priceListColor = {
0: 0.8,
10: 0.7,
25: 0.6,
50: 0.5,
100: 0.4,
250: 0.35,
500: 0.3,
1000: 0.25,
2000: 0.2,
5000: 0.18
}
// Defining the black and white pricelist
var priceListBlackAndWhite = {
0: 0.1,
10: 0.09,
25: 0.08,
50: 0.07,
100: 0.06,
500: 0.05,
1000: 0.045,
5000: 0.04
}
// Defining the pricelist for paperweight
var priceListPaperWeight = {
80: 0,
120: 0.05,
160: 0.1,
190: 0.15,
210: 0.2,
250: 0.25,
280: 0.3,
300: 0.35,
350: 0.4,
351: 0
}
// Defining the pricelist for binding
var priceListBinding = {
0: 3,
10: 2.75,
25: 2.5
}
// Defining the pricelist for stapling
var priceListStaples = {
0: 0.15,
100: 0.12,
250: 0.10,
500: 0.08
}
// Defining the pricelist for stapling
var priceListHoles = {
0: 0.15,
100: 0.12,
250: 0.10,
500: 0.08
}
// Getting the value for the amount of pages given in by user
function finalAmountOfPages() {
var totalAmountOfSets = elems.amountOfSetsInput.value || 0;
var totalAmountOfPages = elems.amountOfPagesInput.value || 0;
// Validation process, returns true or false; if true we proceed
if (validateForm(totalAmountOfSets, totalAmountOfPages)) {
totalAmountOfPages = parseInt(totalAmountOfPages);
totalAmountOfSets = parseInt(totalAmountOfSets);
// Calculating total amount of pages
var finalPagesAmount = totalAmountOfPages * totalAmountOfSets;
// Calculating price per page
var pricePerColorPage = findPricePerColorPage(finalPagesAmount, 0);
var pricePerBlackAndWhitePage = findPricePerBlackAndWhitePage(finalPagesAmount, 0);
var totalPriceColorPrinting = (totalAmountOfPages * totalAmountOfSets) * pricePerColorPage;
var totalPriceBlackAndWhitePrinting = (totalAmountOfPages * totalAmountOfSets) * pricePerBlackAndWhitePage;
// Calculating price for binding
var bindingPrice = findBindingPrice(totalAmountOfSets, 0);
var totalBindingPrice = totalAmountOfSets * bindingPrice;
// Calculating price for paper weight
var paperWeightPricePerPage = findPaperWeightPrice(paperWeight, 0)
var totalPricePaper = (totalAmountOfSets * totalAmountOfPages) * paperWeightPricePerPage;
var totalPricePaperDoubleSided = (totalAmountOfSets * (totalAmountOfPages / 2)) * paperWeightPricePerPage;
// Setting the startup costs
var startUpCosts = 2.95;
// Calculation price for stapling and making holes
var staplePrice = findStaplePrice(totalAmountOfSets, 0);
var holesPrice = findHolesPrice(totalAmountOfSets, 0);
var totalStaplePrice = totalAmountOfSets * staplePrice;
var totalHolesPrice = totalAmountOfSets * holesPrice;
// Calculating total price
var totalColorPrice = totalPriceColorPrinting + totalPricePaper + totalBindingPrice + startUpCosts || 0;
var totalBlackAndWhitePrice = totalPriceBlackAndWhitePrinting + totalPricePaper + totalBindingPrice + startUpCosts || 0;
// Calling the updateView function
//COMMENT 8 first see COMMENT 7. Instead of passing a list of parametres, pass an object
/* updateView({
totalAmountOfSets : totalAmountOfSets,
totalAmountOfPages: totalAmountOfPages
})*/
updateView({
totalAmountOfSets: totalAmountOfSets,
totalAmountOfPages: totalAmountOfPages,
totalColorPrice: totalColorPrice,
totalBlackAndWhitePrice: totalBlackAndWhitePrice,
pricePerColorPage: pricePerColorPage,
pricePerBlackAndWhitePage: pricePerBlackAndWhitePage,
paperWeightPricePerPage: paperWeightPricePerPage,
totalPricePaper: totalPricePaper,
totalPricePaperDoubleSided: totalPricePaperDoubleSided,
bindingPrice: bindingPrice,
totalBindingPrice: totalBindingPrice,
totalPriceBlackAndWhitePrinting: totalPriceBlackAndWhitePrinting,
totalPriceColorPrinting: totalPriceColorPrinting,
startUpCosts: startUpCosts,
totalHolesPrice: totalHolesPrice,
totalStaplePrice: totalStaplePrice
});
// Calling the function the show the calculation table
showCalculation();
}
}
//COMMENT 7 Instead of "geen" it's better to use "0". I understand that you use it as a value for the resulting offerte so let's save this thing for the next iteration. The best practice is to separate the labels from the values and keep values in an "international form", sometimes numeric. So if the user selects option with value 2, you have somewhere an object where you see that number 2 corresponds to "Color black" and then you show the words "Color black" in the offerte. So in the future we'll rewrite it this way.
function toggleVisibility(selector, hide){
var showStyle = hide ? "none" : "";
selector.style.display = showStyle;
}
// Defining a function to hide 'makingStaples' and 'makingHoles' when binding is different from "geen"
function toggleBinding (){
if (getValue(selectedBinding) !== "geen") {
toggleVisibility(elems.staplesSelect, true);
toggleVisibility(elems.holeSelect, true);
} else {
toggleVisibility(elems.staplesSelect, false);
toggleVisibility(elems.holeSelect, false);
}
}
// Defining a function to hide 'makingBinding' and 'makingHoles' when staples is different from "geen"
function toggleStapling (){
if (getValue(selectedStaples) !== "geen") {
toggleVisibility(elems.bindingSelect, true);
toggleVisibility(elems.holeSelect, true);
} else {
toggleVisibility(elems.bindingSelect, false);
toggleVisibility(elems.holeSelect, false);
}
}
// Defining a function to hide 'makingStaples' and 'makingBinding' when holes is different from "geen"
function toggleHoles (){
if (getValue(selectedHoles) !== "geen") {
toggleVisibility(elems.staplesSelect, true);
toggleVisibility(elems.bindingSelect, true);
} else {
toggleVisibility(elems.staplesSelect, false);
toggleVisibility(elems.bindingSelect, false);
}
}
// Function to show the calculation table after pressing the button
function showCalculation() {
toggleVisibility(elems.calculation, false);
}
// Defining a function to validate all fields
function validateForm(totalAmountOfSets, totalAmountOfPages) {
elems.amountOfSetsResults.innerHTML = "";
elems.amountOfPagesResults.innerHTML = "";
// Validating the input fields
if (!totalAmountOfPages || isNaN(totalAmountOfPages) || totalAmountOfPages <= 0) {
elems.amountOfPagesResults.innerHTML = "Controleer uw invoer!";
return false; //validation not passed
} else if (!totalAmountOfSets || isNaN(totalAmountOfSets) || totalAmountOfSets <= 0) {
elems.amountOfSetsResults.innerHTML = "Controleer uw invoer!";
return false; //validation not passed
} else {
return true; //validation passed
}
}
// Defining a price per page for color prints
function findPricePerColorPage(numberOfPages, initialNumber) {
pricePerColorPage = initialNumber;
for (var amount in priceListColor) {
if (numberOfPages > amount) {
pricePerColorPage = priceListColor[amount]
}
}
return pricePerColorPage;
}
// Defining a price per page for black and white prints
function findPricePerBlackAndWhitePage(numberOfPages, initialNumber) {
pricePerBlackAndWhitePage = initialNumber;
for (var amount in priceListBlackAndWhite) {
if (numberOfPages > amount) {
pricePerBlackAndWhitePage = priceListBlackAndWhite[amount]
}
}
return pricePerBlackAndWhitePage;
}
/* Getting the binding value
function getBinding(selectedBinding) {
var b = elems.binding;
var selectedBinding = b.options[b.selectedIndex].value;
return selectedBinding;
}
// Getting the holes value
function getHoles(selectedHoles) {
var h = elems.holes;
var selectedHoles = h.options[h.selectedIndex].value;
return selectedHoles;
}
// Getting the paper weight value
function getPaperWeight(selectedPaperWeight) {
var pW = elems.paperWeight;
var selectedPaperWeight = pW.options[pW.selectedIndex].value;
return selectedPaperWeight;
}
*/
// Getting the text from staples, holes, binding and paperweight
function getText(textBinding, textStapling, textHoles, textPaperWeight) {
var b = elems.binding;
var s = elems.stapling;
var h = elems.holes;
var p = elems.paperWeight;
var textBinding = b.options[b.selectedIndex].text;
var textStapling = s.options[s.selectedIndex].text;
var textHoles = h.options[h.selectedIndex].text;
var textPaperWeight = p.options[p.selectedIndex].text;
return textBinding, textStapling, textHoles, textPaperWeight;
}
// Getting the value from staples, holes, binding and paperweight
function getValue(selectedStapling, selectedBinding, selectedHoles, selectedPaperWeight) {
var b = elems.binding;
var s = elems.stapling;
var h = elems.holes;
var p = elems.paperWeight;
var selectedStapling = s.options[s.selectedIndex].value;
var selectedBinding = b.options[b.selectedIndex].value;
var selectedHoles = h.options[h.selectedIndex].value;
var selectedPaperWeight = p.options[p.selectedIndex].value;
return selectedStapling, selectedBinding, selectedHoles, selectedPaperWeight;
}
// Defining the price for binding
function findBindingPrice(totalAmountOfSets, initialNumber) {
var bindingPrice = initialNumber;
if (getValue(selectedBinding) === "geen") {
return bindingPrice = 0;
} else {
for (var amount in priceListBinding) {
if (totalAmountOfSets > amount) {
bindingPrice = priceListBinding[amount]
}
}
}
return bindingPrice;
}
// Defining the price for making staples
function findStaplePrice(totalAmountOfSets, initialNumber) {
var staplePrice = initialNumber;
if (getValue(selectedStaples) === "geen") {
return staplePrice = 0;
} else {
for (var amount in priceListStaples) {
if (totalAmountOfSets > amount) {
staplePrice = priceListStaples[amount]
}
}
}
return staplePrice;
}
//COMMENT 5 this function is almost identical with getStaples(). Let's remove it and modify getStaples is some way to always use it. Maybe we will pass element as the second parameter?
// Defining the price for making holes
function findHolesPrice(totalAmountOfSets, initialNumber) {
var holesPrice = initialNumber;
if (getValue(selectedHoles) === "geen") {
return holesPrice = 0;
} else {
for (var amount in priceListHoles) {
if (totalAmountOfSets > amount) {
holesPrice = priceListHoles[amount]
}
}
}
return holesPrice;
}
//COMMENT 6 this function is almost identical with getStaples(). Let's remove it and modify getStaples is some way to always use it. Maybe we will pass element as the second parameter?
// Defining a paper weight price
function findPaperWeightPrice(paperWeight, initialNumber) {
paperWeightPricePerPage = initialNumber;
for (var amount in priceListPaperWeight) {
if (getValue(selectedPaperWeight) >= amount) {
paperWeightPricePerPage = priceListPaperWeight[amount]
}
}
return parseFloat(paperWeightPricePerPage);
}
// Defining a function to update the price
function updateView(amount) {
elems.bindingResults.innerHTML = "\u20ac " + amount.totalBindingPrice.toFixed(2);
elems.holesResults.innerHTML = "\u20ac " + amount.totalHolesPrice.toFixed(2);
elems.staplingResults.innerHTML = "\u20ac " + amount.totalStaplePrice.toFixed(2);
elems.totalAmountOfPagesResults.innerHTML = amount.totalAmountOfSets * amount.totalAmountOfPages;
elems.paperWeightResults.innerHTML = getText(textPaperWeight) + " gr.";
elems.bindingMethod.innerHTML = getText(textBinding);
elems.staplingMethod.innerHTML = getText(textStaples);
elems.holesMethod.innerHTML = getText(textHoles);
if (elems.doubleSided.checked) {
elems.pricePaperWeightResults.innerHTML = "\u20ac " + amount.totalPricePaperDoubleSided.toFixed(2);
} else {
elems.pricePaperWeightResults.innerHTML = "\u20ac " + amount.totalPricePaper.toFixed(2);
}
// Making the decision to show black and white totalprice and price per page
if (elems.blackAndWhite.checked) {
elems.colorResults.innerHTML = "Zwart-Wit"
elems.totalPricePrints.innerHTML = "\u20ac " + amount.totalPriceBlackAndWhitePrinting.toFixed(2);
elems.totalPrice.innerHTML = "\u20ac " + amount.totalBlackAndWhitePrice.toFixed(2);
elems.pricePerPageResults.innerHTML = "\u20ac " + amount.pricePerBlackAndWhitePage.toFixed(2);
}
// or to show the color totalprice and price per page
else {
elems.colorResults.innerHTML = "Kleur"
elems.totalPricePrints.innerHTML = "\u20ac " + amount.totalPriceColorPrinting.toFixed(2);
elems.totalPrice.innerHTML = "\u20ac " + amount.totalColorPrice.toFixed(2);
elems.pricePerPageResults.innerHTML = "\u20ac " + amount.pricePerColorPage.toFixed(2);
}
}
// Defining an Event Listener with an on click function
elems.calculate.addEventListener("click", finalAmountOfPages);
// Defining the Event Listeners to hide or show 'makingHoles', 'makingStaples' and 'binding'
elems.stapling.addEventListener("change", toggleStapling);
elems.binding.addEventListener("change", toggleBinding);
elems.holes.addEventListener("change", toggleHoles);
<h1>Bereken de kosten</h1>
<table>
<!-- Ask the user to enter the amount of pages -->
<tr>
<td><p>Aantal pagina's:</p></td>
<td><p><input type="number" id="amountOfPagesInput"></p></td>
<td><p id="amountOfPagesResults"></p></td>
<td></td>
</tr>
<!-- Ask the user to enter the amount of sets -->
<tr>
<td><p>Aantal sets:</p></td>
<td><p><input type="number" id="amountOfSetsInput"></p></td>
<td><p id="amountOfSetsResults"></p></td>
<td></td>
</tr>
<!-- Ask user for color of the print / standard selected is color -->
<tr>
<td><p>Kleur van afdruk: </p></td>
<td>
<p>
<input type="radio" value="kleur" name="pickYourColor" id="color" checked="true"> Kleur
<br/>
<input type="radio" value="zwart-wit" name="pickYourColor" id="blackAndWhite"> Zwart-Wit
</p>
</td>
<td></td>
<td></td>
</tr>
<!-- Ask the user if he wants single or double sided prints / standard selected is single sided -->
<tr>
<td><p>Enkel of dubbelzijdig: </p></td>
<td>
<p>
<input type="radio" value="enkelzijdig" name="singleOrDoubleSided" id="singleSided" checked="true"> Enkelzijdig
<br/>
<input type="radio" value="dubbelzijdig" name="singleOrDoubleSided" id="doubleSided"> Dubbelzijdig
</p>
</td>
<td></td>
<td></td>
</tr>
<!-- Ask the user which paperweight he wants -->
<tr>
<td><p>Papierdikte: </p></td>
<td>
<p>
<select id="paperWeight">
<option value="80" id="80gr">Standaard papier</option>
<option value="120" id="120gr">120 grams + € 0,05</option>
<option value="160" id="160gr">160 grams + € 0,10</option>
<option value="190" id="190gr">190 grams + € 0,15</option>
<option value="210" id="210gr">210 grams + € 0,20</option>
<option value="250" id="250gr">250 grams + € 0,25</option>
<option value="280" id="280gr">280 grams + € 0,30</option>
<option value="300" id="300gr">300 grams + € 0,35</option>
<option value="350" id="350gr">350 grams + € 0,40</option>
</select>
</p>
</td>
<td></td>
<td></td>
</tr>
<!-- Specifing the binding -->
<tr id="makingBinding">
<td><p>Inbinden: </p></td>
<td>
<p>
<select id="binding">
<option value="geen" id="none">-- Niet inbinden --</option>
<option value="wire-o" id="wire-o">Wire-O ringband</option>
<option value="thermo" id="thermo">Thermo lijmstrip</option>
</select>
</p>
</td>
<td></td>
<td></td>
</tr>
<tr id="makingStaples">
<td><p>Nieten: </p></td>
<td>
<p>
<select id="stapling">
<option value="geen" id="none">-- Niet nieten --</option>
<option value="1" id="1left">1 nietje links</option>
<option value="2" id="1right">1 nietje rechts</option>
<option value="3" id="1left">2 nietjes links</option>
<option value="4" id="foldAndStaple">vouwen + nieten</option>
</select>
</p>
</td>
<td></td>
<td></td>
</tr>
<tr id="makingHoles">
<td><p>Perforeren: </p></td>
<td>
<p>
<select id="holes">
<option value="geen" id="none">-- Niet perforeren --</option>
<option value="2 gaten" id="2holes">2 gaten</option>
<option value="4 gaten" id="4holes">4 gaten</option>
</select>
<p>
</td>
<td></td>
<td></td>
</tr>
</table>
<input type="button" id="calculate" value="Berekenen">
<hr/>
<!-- Start calculation -->
<table id="calculation">
<tr>
<td><h2>Uw Offerte:</h2></td>
</tr>
<!-- Show the amount of pages -->
<tr>
<td><p>Totaal aantal pagina's:</p></td>
<td><p id="totalAmountOfPagesResults"></p></td>
<!-- Show the total price -->
<td><p>Prijs per zijde:</p> </td>
<td><p id="pricePerPageResults"></p></td>
</tr>
<tr>
<td><p>Kleur of Zwart-wit:</p></td>
<td><p id="colorResults"></p></td>
<td><p>Totaal voor printen: </p></td>
<td><p id="totalPricePrints"></p></td>
</tr>
<!-- Show the price for paper weight -->
<tr>
<td><p>Papierdikte: </p></td>
<td><p id="paperWeightResults"></p></td>
<!-- Show the total price -->
<td><p>Totaal voor papier: </p></td>
<td><p id="pricePaperWeightResults"></p></td>
</tr>
<!-- Show the chosen binding method -->
<tr>
<td><p>Inbindmethode: </p></td>
<td><p id="bindingMethod"></p></td>
<!-- Show the total price -->
<td><p>Totaal voor inbinden: </p></td>
<td><p id="bindingResults"></p></td>
</tr>
<!-- Show the chosen stapling method -->
<tr>
<td><p>Nietjes: </p></td>
<td><p id="staplingMethod"></p></td>
<!-- Show the total price -->
<td><p>Totaal voor nieten: </p></td>
<td><p id="staplingResults"></p></td>
</tr>
<!-- Show the chosen binding method -->
<tr>
<td><p>Perforatie: </p></td>
<td><p id="holesMethod"></p></td>
<!-- Show the total price -->
<td><p>Totaal voor perforeren: </p></td>
<td><p id="holesResults"></p></td>
</tr>
<!-- Show startup costs -->
<tr>
<td></td>
<td></td>
<td><p>Opstartkosten: </p></td>
<td><p>€ 2,95</p></td>
</tr>
<!-- Show the price per page -->
<tr>
<td></td>
<td></td>
<td><h3>Totaalprijs: </h3></td>
<td><h3 id="totalPrice"></h3></td>
</tr>
</table>
Uncaught ReferenceError: selectedBinding is not defined.
// Defining a function to hide 'makingStaples' and 'makingHoles' when binding is different from "geen"
function toggleBinding (){
if (getValue(selectedBinding) !== "geen") {
toggleVisibility(elems.staplesSelect, true);
toggleVisibility(elems.holeSelect, true);
} else {
toggleVisibility(elems.staplesSelect, false);
toggleVisibility(elems.holeSelect, false);
}
}
This function uses selectedBinding but this is not defined before this function is called. Declare a variable selectedBinding before using it.
Uncaught ReferenceError: selectedStaples is not defined
// Defining a function to hide 'makingBinding' and 'makingHoles' when staples is different from "geen"
function toggleStapling (){
if (getValue(selectedStaples) !== "geen") {
toggleVisibility(elems.bindingSelect, true);
toggleVisibility(elems.holeSelect, true);
} else {
toggleVisibility(elems.bindingSelect, false);
toggleVisibility(elems.holeSelect, false);
}
}
Again the same issue here. There is no declaration of selectedStaples.
Similar issue is with selectedHoles.
I see in your code you are actually making a declaration in the commented code of yours:
/* Getting the binding value
function getBinding(selectedBinding) {
var b = elems.binding;
var selectedBinding = b.options[b.selectedIndex].value;
return selectedBinding;
}
When you declare a variable inside a function, you are limiting its scope to the function. Which means that this will not be available outside the function. Your need to declare these variables so that they are available to functions like toggleBinding etc and it will fix your current issue.

Categories