Calculate cell value using selected option in table - javascript

I'm trying to build a single table that houses all of the pricing options I need. This should be simple, but I'm getting NaN responses in the cell meant to contain the calculation.
<!DOCTYPE html>
<html>
<body>
<table border="2">
<tr>
<th>Subscription Memberships</th>
</tr>
<tr>
<td>Subscription Type:
<select id="duration">
<option value="1MonthSub">Monthly Subscription</option>
<option value="3MonthSub">Quarterly Subscription</option>
<option value="6MonthSub">Bi-Annual Subscription</option>
<option value="yearSub">Yearly Subscription</option>
</select>
<br>
<input type="checkbox" id="discount">
I am eligible for the student, military, or senior discount.</td>
</tr>
<tr>
<td><span id="calculated"></span></td>
</tr>
</table>
<script>
function calcPrice() {
//Variables
var choice = document.getElementById("duration");
var dur = choice.options[choice.selectedIndex].text;
var price;
var per;
var output;
switch(dur) {
case "1MonthSub":
price = 65;
per = " / month";
break;
case "3MonthSub":
price = 220;
per = " / 3 months";
break;
case "6MonthSub":
price = 440;
per = " / 6 months";
break;
case "yearSub":
price = 900;
per = " / year";
break;
}//end switch
if (document.getElementById("discount").checked) {
price = price * 0.9;
}//end if
output = price + per;
return output;
}//end calcPrice()
document.getElementById("calculated").innerHTML = calcPrice();
</script>
</body>
</html>
The NaN cell SHOULD calculate the price based on the option selected from the dropdown and the true/false value of the checkbox. I've tried moving the script portions around, and when they're placed before the table nothing shows up in the cell at all. What am I missing here?

I changed:
var dur = choice.options[choice.selectedIndex].text;
To:
var dur = choice.options[choice.selectedIndex].value;
<!DOCTYPE html>
<html>
<body>
<table border="2">
<tr>
<th>Subscription Memberships</th>
</tr>
<tr>
<td>Subscription Type:
<select id="duration">
<option value="1MonthSub">Monthly Subscription</option>
<option value="3MonthSub">Quarterly Subscription</option>
<option value="6MonthSub">Bi-Annual Subscription</option>
<option value="yearSub">Yearly Subscription</option>
</select>
<br>
<input type="checkbox" id="discount">
I am eligible for the student, military, or senior discount.</td>
</tr>
<tr>
<td><span id="calculated"></span></td>
</tr>
</table>
<script>
function calcPrice() {
//Variables
var choice = document.getElementById("duration");
var dur = choice.options[choice.selectedIndex].value;
var price;
var per;
var output;
switch(dur) {
case "1MonthSub":
price = 65;
per = " / month";
break;
case "3MonthSub":
price = 220;
per = " / 3 months";
break;
case "6MonthSub":
price = 440;
per = " / 6 months";
break;
case "yearSub":
price = 900;
per = " / year";
break;
}//end switch
if (document.getElementById("discount").checked) {
price = price * 0.9;
}//end if
output = price + per;
return output;
}//end calcPrice()
document.getElementById("calculated").innerHTML = calcPrice();
</script>
</body>
</html>

Related

Calculate and Passing Value from select option to input box

I'm new to HTML and JavaScript. I need to do a website where it requires to sum up the Total value based on the select options. After that, pass the value back to the input in HTML.
HTML code
<select class="normalinput" name="giftname" id="giftname" onchange="populate('giftname')">
<option value="None">None</option>
<option value="G0001">Big Graduation Bear +RM60.00</option>
<option value="G0002">Small Graduation Bear +RM20.00</option>
<option value="G0003">Handcraft Gift Card +RM5.00</option>
<option value="G0004">Valentine Gift Card +RM10.00</option>
<option value="G0005">Godiva Chocolate Box +RM100.00</option>
<option value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total"></p>
JavaScript Code
<script type="text/javascript">
function populate(giftname) {
var giftname = document.getElementById(giftname);
var gg = giftname.options[giftname.selectedIndex].value;
var total;
if (gg.value == "G0001") {
total = 90 + 60;
document.getElementById("total").value = total;
}
else if (gg.value == "G0002") {
total = 90 + 20;
document.getElementById("total").value = total;
}
else if (gg.value == "G0003") {
total = 90 + 5;
document.getElementById("total").value = total;
}
else if (gg.value == "G0004") {
total = 90 + 10;
document.getElementById("total").value = total;
}
else if (gg.value == "G0005") {
total = 90 + 100;
document.getElementById("total").value = total;
}
else if (gg.value == "G0006") {
total = 90 + 90;
document.getElementById("total").value = total;
}
else
total = 90;
document.getElementById("total").value = total;
}
</script>
A screenshot of result needed
Thank you so much.
You can add a data attribute to your HTML option elements to contain the price and use it to compute your total price.
<select class="normalinput" name="giftname" id="giftname" onchange="populate('giftname')">
<option data-price="0" value="None">None</option>
<option data-price="60" value="G0001">Big Graduation Bear +RM60.00</option>
<option data-price="20" value="G0002">Small Graduation Bear +RM20.00</option>
<option data-price="5" value="G0003">Handcraft Gift Card +RM5.00</option>
<option data-price="10" value="G0004">Valentine Gift Card +RM10.00</option>
<option data-price="100" value="G0005">Godiva Chocolate Box +RM100.00</option>
<option data-price="90" value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total"></p>
<script type="text/javascript">
populate('giftname');
function populate(giftnameId) {
var giftnameSelect = document.getElementById(giftnameId); // Select dropdown
let selectedOption = giftnameSelect.options[giftnameSelect.selectedIndex]; // Selected option
// Get the selected value. We need the plus to parse it to a number, because initially its a string.
var selectedGiftnameValue = +selectedOption.dataset.price;
var total = 90 + selectedGiftnameValue;
document.getElementById("total").value = total;
}
</script>
You can try a more simple approach.
Assuming you want a dollar value I added
return total.value = Number.parseFloat(price).toFixed(2);
if not replace the above line with
total.value = price;
var price;
var total = document.getElementById('total');
var gg = document.getElementById('giftname');
gg.onchange = function() {
if (gg.value == "G0001") {
price = 90 + 60;
}
else if (gg.value == "G0002") {
price = 90 + 20;
}
else if (gg.value == "G0003") {
price = 90 + 5;
}
else if (gg.value == "G0004") {
total = 90 + 10;
}
else if (gg.value == "G0005") {
price = 90 + 100;
}
else if (gg.value == "G0006") {
price = 90 + 90;
}
else {
price = 90;
}
return total.value = Number.parseFloat(price).toFixed(2);
}
<select class="normalinput" name="giftname" id="giftname" \>
<option value="None">None</option>
<option value="G0001">Big Graduation Bear +RM60.00</option>
<option value="G0002">Small Graduation Bear +RM20.00</option>
<option value="G0003">Handcraft Gift Card +RM5.00</option>
<option value="G0004">Valentine Gift Card +RM10.00</option>
<option value="G0005">Godiva Chocolate Box +RM100.00</option>
<option value="G0006">Ferrero Rocher Love Box +RM90.00</option>
</select>
<p class="total"> Total: RM <input type="number" name="total" id="total" ></p>

Why does my function not fetch the value of variable?

The purpose of the code is to compute for the car market value. If If Age of the Car is :
1 - then subtract 20% from the Price of the Car
2 - then subtract 35% from the Price of the Car
3 - 7 - then subtract 35% from the Price of the Car and then subtract 10%
more for each year starting from the 3rd year.
8 - 10 - then the market value is fixed at 100,000.00
More than 10 years then the market value is fixed at 75,000.00.
Then it will display the name inputted and the value of the car but it doesnt seem to work. pls help
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
function calculateValue() {
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}
<h1>Car Market Value Calculator</h1>
<form>
Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br> Age of Car
<select id="age">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3-7</option>
<option value="3">8-10</option>
<option value="4">more than 10</option>
</select><br> Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000"><br>
<p>Good Condition?</p>
Yes <input id="condition" type="radio" name="condition" value="0"> No <input id="condition" type="radio" name="condition" value="1">
<button type="button" name="submit" onclick="calculateValue()">Submit</button>
</form>
<p id="message"></p>
You have a few errors in your code:
You're not getting the input from the dom at the right moment. You should get the input values before calculation, not when the script loads. This ensures that the DOM is loaded, and get the right values.
The age value is not calculated properly. Don't use select for numeric values. Also, read again your case price = 2 ;)
This code does what you expect:
const calculateValue = () => {
let age = +document.querySelector('input[name=age]').value,
price = +document.querySelector('input[name=price]').value,
condition = document.querySelector('input[name=condition]').checked;
// depreciate based on age
if (age==1) price*=.8
else if (age==2) price*=.65
else if (age>2 && age<8) price*=(.65-(age-3)*.1)
else if (age>7 && age<11) price = 100000
else price = 75000;
// depreciate based on condition
if (!condition) price*=.9;
console.log(price);
}
<div>
<input name="age" type="number" placeholder="age">
</div>
<div>
<input name="price" type="number" placeholder="price">
</div>
<div>
Good condition?
<input name="condition" type="radio" value="true" checked>yes
<input name="condition" type="radio" value="false">no
</div>
<button onclick="calculateValue()">Compute</button>
If you open your browser's development console you'll see an error indicating that you're trying to get the .value of something that is null or undefined. Because document.getElementById("price") doesn't find anything when you're executing it.
You're trying to get the values of your inputs before the user has typed anything. Before the inputs have even been rendered on the page even.
You don't want to get the values until the user has pressed the button. So move that code into the function:
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
//... the rest of your function
}
You need to move the first 6 lines where you are trying to get the values from input inside your calculateValue() function
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
...
Simply do this and your code will work fine.
Explanation: You need to get the new values from the input boxes each time the submit button is pressed. What you have done is that you have taken the values from the input boxes only once. As you move these lines inside the function, the fresh values are taken each time the button is pressed.
The document.getElementById commands will execute before the HTML markup is loaded, and hence will trigger an error. You can fix it by moving the variable declarations and value-fetching into the function:
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
...etc...
You will want to do this anyway, since your code needs to fetch the current input values every time you click "submit".
Get values of your variables inside the calculate value function
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Car Market Value Calculator">
<meta name="keywords" content="calculator, car, market, value">
<meta name="author" content=", 26/02/19">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<h1>Car Market Value Calculator</h1>
<form>
Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br>
Age of Car<select id="age">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3-7</option>
<option value="3">8-10</option>
<option value="4">more than 10</option>
</select><br>
Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000" ><br>
<p>Good Condition?</p>
Yes <input id="condition" type="radio" name="condition" value="0">
No <input id="condition" type="radio" name="condition" value="1">
<button type="button" name="submit" onclick = "calculateValue()">Submit</button>
</form>
<p id="message"></p>
</body>
<script>
function calculateValue(){
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
alert(price);
switch (age) {
case 0:
price = price - 0.20*price;
break;
case 1:
price = price - 0.35*price;
break;
case 2:
price = price - 0.35*price - (age-3)*.10*price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch(condition){
case 0:
price = price;
break;
case 1:
price = price- price*.10;
break;
}
document.getElementById("message").innerHTML = "Your"+ name +" is valued at "+price+"today";
}
</script>
</html>
Every time you click the submit you need to get the input values again, and not only when loading the page. Just move the 'var' declarations into the function:
function calculateValue() {
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var price = document.getElementById("price").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}
Solution at Codepen
function calculateValue() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;
age = parseInt(age);
condition = parseInt(condition);
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}
switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}
document.getElementById("message").innerHTML="Your"+name+" is valued at "+price+ "
today";
}`
The comments given by others are correct. You need to get the updated values on click of the submit button and hence all the variable will come inside the calculateValue function.
Wrap all the code in the document.ready method.

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.

Resetting a page after loop has finished

I am creating a dice game. I am trying to make it so the user can re-click a button after the loop as gone through to reset the page to play again. My gut tells me an if statement is involved but after several attempts I cannot figure out how to set it up.
I was able to change the button value to show "play again" after pressed, I just need to get the page to reload after the user re-presses the button "play again." Any help would be appreciated thanks.
<script>
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
function rollDice() {
do {
count++;
var userInput = parseInt(document.getElementById("bet").value);
var wallet = userInput;
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
rolls.push(diceTotal);
rollCountMoney.push(wallet);
if(wallet > maxMoney){
maxMoney = wallet;
mostRoll = count - 1;
}
if(userInput > startingBet){
betStarter.push(userInput);
}
if (diceTotal === 7) {
document.getElementById("bet").value = wallet += 4;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You win $4 for a total of: " +wallet);
} else {
document.getElementById("bet").value = wallet -= 1;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You lose $1 for a total of: " +wallet);
}
} while (wallet > 0) {}
var displayMsg = count;
var highest = maxMoney;
var highestRoll = mostRoll;
document.getElementById("display").innerHTML = displayMsg;
document.getElementById("starter").innerHTML = betStarter[0];
document.getElementById("highPot").innerHTML = highest;
document.getElementById("rollPot").innerHTML = highestRoll;
var elem = document.getElementById("playAgain");
if (elem.value=="Play Again"){
elem.value = "Play";
}else {elem.value = "Play Again";
}
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="page-head">
<h1 align="center">Lucky Sevens</h1>
</div>
</div>
<div class="container" align="center">
<table class="table-responsive">
<tr>
<th><h3 align="center"><b>Lucky Sevens</b></h3></th>
</tr>
<tr>
<td>
<form>
Starting Bet:
<input id="bet" type="text"/>
</form>
</td>
</tr>
<tr>
<td align="center">
<form>
<input type="button" id="playAgain" onclick="rollDice()" value="Play"></input>
</form>
</td>
</tr>
</table>
<div class="jumbotron" style="width:400px; position: relative; top: 40px">
<table class="dicey" border="1" style="border-color: white">
<caption ALIGN="top">
<h3 align="center" style="color: black"><b><u>Results</u></b></h3>
</caption>
<tr>
<th style= "background-color: grey"><b>Starting Bet</b></th>
<th style= "background-color: grey" id="starter"></th>
</tr>
<tr>
<td>Total rolls before going broke </td>
<td id="display"></td>
</tr>
<tr>
<td>Highest amount won </td>
<td id="highPot"></td>
</tr>
<tr>
<td>Roll count at highest amount won </td>
<td id="rollPot"></td>
</tr>
</table>
</div>
</div>
If I understood your code correctly, you can either reload the page:
function rollDice(){
if (document.getElementById("playAgain").value=="Play Again")
location.reload();
...
or reset it to the initial state:
function rollDice() {
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
document.getElementById("display").innerHTML = "";
document.getElementById("starter").innerHTML = "";
document.getElementById("highPot").innerHTML = "";
document.getElementById("rollPot").innerHTML = "";
...
The simplest way would be to add a second button for play again like
<button id="play-again-button" style="display:none" onclick="location.reload()">play again</button >
Then show it when you need to via
document.getElementById("play-again-button').style.display = "block";
If you want to actually refresh the page. Or tie that button's onclick to a js function that resets things.

get random objects from a separate file

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]);

Categories