Calculation not working when value with comma - javascript

Used below HTML & JS to calculate total value based on increment/decrement. It works fine if value without comma. 6300, 1200. When we add comma like 6,300 or 1,200. Below calculation method not working.
Hope i missed the logic to calculate with comma.. not sure which one i missed out.
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function(){
let packageamount = parseInt($('.package-amount .amount').html());
let perpersonamount = parseInt($('.per-person-cost').html());
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)+1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount);
} else if ($(this).hasClass('decreasepax')){
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>

You can simply use replace function to remove , comma with nothing. Your calculations will be perfect. Also, I would rec-emend using .text() not .html
When you use parseInt on a text or html and it has commas it will take the first value(character) which will be 1 in 1,200 and 6 in 6,300.
If you thinking of displaying the Total or Grand Total with commas added just use toLocaleString to show the number with commas added.
Demo
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function() {
let packageamount = $('.package-amount .amount').text().replace(',', '');
let perpersonamount = $('.per-person-cost').text().replace(',', '');
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')) {
$(noofpaxinput).val(parseInt(txtnoofpaxValue) + 1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
} else if ($(this).hasClass('decreasepax')) {
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue) - 1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue) - 1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount.toLocaleString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>

You could use:
.replace(/,/g, '') to remove comma before parse
.toLocaleString() to print number with comma after calculation
let packageamount = parseInt($('.package-amount .amount').html().replace(/,/g, ''));
// ...
totalAmount.html(grandTotalAmount.toLocaleString());
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function(){
let packageamount = parseInt($('.package-amount .amount').html().replace(/,/g, ''));
let perpersonamount = parseInt($('.per-person-cost').html().replace(/,/g, ''));
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)+1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
} else if ($(this).hasClass('decreasepax')){
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>

Related

How to implement a function that obtains the percentage corresponding to each counter?

The percentage will be updated depending on the two counters. I have to have as total data the sum of counter and counter1
var botonElement = document.getElementById("botonClick");
var pElement = document.getElementById("areaContador");
var pPorce = document.getElementById("porcen");
var contador = 0;
var botonElement1 = document.getElementById("botonClick1");
var pElement1 = document.getElementById("areaContador1");
var pPorce1 = document.getElementById("porcen1");
var contador1 = 0;
botonElement.onclick = function () {
contador++;
pElement.textContent = contador;
/* pPorce.textContent = result + "%"; */
}
botonElement1.onclick = function () {
contador1++;
pElement1.textContent = contador1;
/* pPorce1.textContent = result + "%"; */
}
Looks like you are looking for something like below.
function increaseCounter(index) {
const countElement1 = document.getElementById("counter1");
const countElement2 = document.getElementById("counter2");
const currentCountElement = document.getElementById("counter" + index);
currentCountElement.value = parseInt(currentCountElement.value) + 1;
const value1 = parseInt(countElement1.value);
const value2 = parseInt(countElement2.value);
const total = value1 + value2;
const perc1 = ((value1/total) * 100).toFixed(2);
const perc2 = ((value2/total) * 100).toFixed(2);
document.getElementById("percentage1").innerHTML = perc1;
document.getElementById("percentage2").innerHTML = perc2;
}
.container {
display: flex;
background-color: #993355;
color: #ffffff;
}
<div class="container">
<div>
<h3>Area 1</h3>
<div>Count: <input type="text" value="0" id="counter1" /></div>
<div>Percentage: <label id="percentage1"></label></div>
<div><button onclick="increaseCounter(1)">Click Here!</button></div>
</div>
<div>
<h3>Area 2</h3>
<div>Count: <input type="text" value="0" id="counter2" /></div>
<div>Percentage: <label id="percentage2"></label></div>
<div><button onclick="increaseCounter(2)">Click Here!</button></div>
</div>
</div>

Incorrect result of loop

I study Java Script and faced the problem that during looping the result of last cycle is inserted not at the last but at first.
My Code:
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
for (let i = 1; i <= document.querySelector('#period').value; i++) {
if (i == 1) {
newPayment = document.querySelector('#cashFlowOne');
newPayment.innerHTML = `<label for="diffCashFlow">Income for period <span id="periodDiff">1 </span></label><input id="diffCashFlow" name="differentCashFlow" type="text"><br><br>`;
} else {
let np = newPayment.cloneNode(true);
np.id = i;
document.querySelector('#periodDiff').innerHTML = i + " ";
payment.append(np);
}
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods">
<div id="cashFlowOne"><span id="periodDiff"></span></div>
</div>
For example, when I insert 5 into input "period", the sequence of results of loop is next:
Income for period 5
Income for period 1
Income for period 2
Income for period 3
Income for period 4
I tried to researched the reason but didn't find it. I will be grateful for any help.
You need to assign the innerHTML of the cloned node, not the original node after you cloned it.
Since IDs shouldn't be repeated, change id="periodDiff" to class="periodDiff".
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType() {
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
for (let i = 1; i <= document.querySelector('#period').value; i++) {
if (i == 1) {
newPayment = document.querySelector('#cashFlowOne');
newPayment.innerHTML = `<label for="diffCashFlow">Income for period <span class="periodDiff">1 </span></label><input class="diffCashFlow" name="differentCashFlow" type="text"><br><br>`;
} else {
let np = newPayment.cloneNode(true);
np.id = i;
np.querySelector(".periodDiff").innerHTML = i + " ";
payment.append(np);
}
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods">
<div id="cashFlowOne"><span id="periodDiff"></span></div>
</div>
you need to create elements using document.createElement instead of relying on building it using .innerHTML which can be risky if misused.
//Determine annuity
const annuity = document.querySelector('#annuityType');
let payment = document.querySelector('#cashFlowType');
function showAnnuity(){
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowType');
payment.innerHTML = `<label for="annuity">Сума ануїтету </label><input id="annuity" name="annuity" type="text"><br><br>`;
}
annuity.onclick = showAnnuity;
//Determine different cash flows
const different = document.querySelector('#differentType');
function showDifferentType(){
payment.innerHTML = ``;
payment = document.querySelector('#cashFlowPeriods');
let newPayment;
let html = '';
for(let i = 1; i <= document.querySelector('#period').value; i++){
let label = document.createElement('label');
let input = document.createElement('input');
let br = document.createElement('br');
input.id = `periodDiff${i}`;
label.htmlFor = input.id;
label.innerText = `Income for period ${i} `;
payment.append(label);
payment.append(input);
payment.append(br);
}
}
different.onclick = showDifferentType;
<div>
<label for="period">Строк проекту (у роках)</label>
<input id="period" name="period" type="text">
</div>
<div>
<p>What kind of payment?</p>
<label for="annuityType">Annuity</label>
<input id="annuityType" name="cashFlowType" type="radio">
<label for="differentType">Different payments</label>
<input id="differentType" name="cashFlowType" type="radio">
</div><br>
<div id="cashFlowType"></div>
<div id="cashFlowPeriods"><div id="cashFlowOne"> <span id="periodDiff"></span></div></div>
<div>

Shopping Cart and Calling Id/classes

ok I fixed most of my issues for my real estate project. The final problem I can't solve is my updateCartTotal Function. I get error message "Can not set property of Undefined at updateCartTotal" I have tried switching between querySelector and getElementsByClassName, taking the zeros out of my function, changing target elements, nothing seems to work. I know it might be something simple but I can't figure it out. HTML file below:
<section class="container content-section">
<h2 class="section-header">View Properties</h2>
<div id="propertyContainer" class="propertyItems1"></div>
</section>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
<span class="cart-item cart-header cart-column">Listing</span>
<span class="cart-avgPrice cart-header cart-column">PRICE</span>
<span class="cart-propType cart-header cart-column">Property Type</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span>
</div>
<button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>
</section>
This is the code I have for my js file:
//Recapture Data
let propertyItems1= document.getElementsByClassName(`#propertyItems1`);
let allItems = propertyContainer.getElementsByClassName(`fullAddress propType avgPrice`);
let data1 = [].map.call(allItems, fullAddress => fullAddress.textContent);
let data2 = [].map.call(allItems, propType => propType.textContent);
let data3 = [].map.call(allItems, avgPrice => fullAddress.textContent);
//Shopping Cart Functionality
if (document.readyState == 'loading') {
document.addEventListner('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
console.log("running the ready() function")
let removeItemButtons = document.getElementsByClassName('btn-danger')
for (let i = 0; i < removeItemButtons.length; i++) {
let button = removeItemButtons[i]
button.addEventListener('click', removeCartItem)
}
let quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (let i = 0; i < quantityInputs.length; i++) {
let input = quantityInputs[i]
input.addEventListner('change', quantityChanged)
}
let addToCartButtons = document.getElementsByClassName('property-item-button')
for (let i = 0; i < addToCartButtons.length; i++) {
let button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank You for purchasing a home')
let cartItems = document.getElementsByClassName('cart-items')[0]
while(cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
let buttonClicked = event.target
buttonClicked.parentElement.remove
updateCartTotal()
}
function quantityChanged(event) {
let input = event.target
if(isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
let button = event.target
let propertyItems1 = button.parentElement
let fullAddress = propertyItems1.querySelector('.fullAddress').innerText
let propType = propertyItems1.getElementsByClassName('propType').innerText
let avgPrice = propertyItems1.getElementsByClassName('avgPrice').innerText
addItemToCart(fullAddress,propType,avgPrice)
updateCartTotal()
}
function addItemToCart(fullAddress, propType, avgPrice) {
let cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
let cartItems = document.getElementsByClassName('cart-items')[0]
let cartItemNames = cartItems.getElementsByClassName('cart-item-fullAddress')
for (var i = 0; i < cartItemNames.length; i++) {
if (cartItemNames[i].innerText == fullAddress) {
alert('This item is already added to the cart')
return
}
}
let cartRowContents = `
<div class="cart-item cart-column">
<span class="fullAddress">${fullAddress}</span>
<span class="propType">${propType}</span>
</div>
<span class="cart-avgPrice cart-column">${avgPrice}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
let cartItemContainer = document.getElementsByClassName('cart-items')[0]
let cartRows = cartItemContainer.getElementsByClassName('cart-row')
let total = 0
for (let i = 0; i < cartRows.length; i++) {
let cartRow = cartRows[i]
let avgPriceElement = cartRow.getElementsByClassName('cart-avgPrice')[0]
let quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
let avgPrice = parseFloat(avgPriceElement.innerText.replace('$', ''))
let quantity = quantityElement.value
total = total + (avgPrice * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-avgPrice')[0].innerText = '$' + total
}
Please help my project is due very soon.
Your class for the cart-avgPrice is spelled wrong. Change
document.getElementsByClassName('cart-total-avgPrice')[0].innerText = '$' + total
to
document.getElementsByClassName('cart-avgPrice')[0].innerText = '$' + total

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 to access the object in my array on function call

I created an array of objects with different properties but I am having problem displaying each properties of my object on the webpage. I have tried but I don't know where the problem is.
I have tried to access the objects individually but still not working please check the problem
//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");
//Event listeners
continued.addEventListener('click', continueAfterIntro);
start.addEventListener('click', startQuiz);
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;
//Array object declaration
let questions = [{
question: "Who is the president Nigeria?",
choiceA: "Muhamadu Buhari",
choiceB: "Osibajo",
choiceC: "Obasanjo",
choiceD: "Green,Red,Green",
correct: "A"
}, {
question: "Who is the governor of oyo state?",
choiceA: "Abiola Ajumobi",
choiceB: "Seyi makinde",
choiceC: "Alao Akala",
choiceD: "Green,Red,Green",
correct: "B"
}, {
question: "What are the colors of the Nigerian Flag?",
choiceA: "Green,White,Blue",
choiceB: "Blue,White,Green",
choiceC: "Green,White,Green",
choiceD: "Green,Red,Green",
correct: "C"
}];
function continueAfterIntro() {
intro.style.display = 'none';
startt.style.display = 'block';
wel.innerHTML = `Hi ${name}`;
}
function renderQuestion() {
let q = questions[runningQuestion];
question.innerHTML = "<p>" + q.question + "</p>";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
}
function startQuiz() {
startt.style.display = "none";
quiz.style.display = "block";
renderQuestion();
}
<div id="container">
<div class="" id="introduction">
<div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
<div id="para1">
<p>Hey there i'm AFO by name whats yours</p>
</div>
<div id="name-button">
<span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
<span id="continue"><input type="button" value="Continue" id="continue"></span>
</div>
</div>
<div id="startt" style="display: none">
<p id="wel"></p>
<div id="start">Start Quiz!</div>
</div>
<div id="quiz" style="display: none">
<div id="question"></div>
<div id="choices">
A.
<div class="choice" id="A" onclick="checkAnswer('A')"></div>
B.
<div class="choice" id="B" onclick="checkAnswer('B')"></div>
C.
<div class="choice" id="C" onclick="checkAnswer('C')"></div>
D.
<div class="choice" id="D" onclick="checkAnswer('D')"></div>
</div>
<div id="timer">
<div id="counter"></div>
<div id="btimeGauge"></div>
<div id="timeGauge"></div>
</div>
<div id="progress"></div>
</div>
<div id="scoreContainer" style="display: none"></div>
</div>
The function renderQuestion should display the questions and the choices on the webpage
When i run your project i got ReferenceError.
Uncaught ReferenceError: Cannot access 'questions' before initialization
That means you can't play around with Questions Array before initialization. For example:
const questionsLength = questions.length; // REFERENCE ERROR.
const questions = ['a', 'b', 'c'];
console.log(questionsLength);
Declare Questions Array before you inspect length:
const questions = ['a', 'b', 'c'];
const questionsLength = questions.length;
console.log(questionsLenght) // Returns 3
Working example:
//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");
//Event listeners
continued.addEventListener('click',continueAfterIntro);
start.addEventListener('click',startQuiz);
//Array object declaration
let questions = [
{
question : "Who is the president Nigeria?",
choiceA : "Muhamadu Buhari",
choiceB : "Osibajo",
choiceC : "Obasanjo",
choiceD : "Green,Red,Green",
correct : "A"
},{
question : "Who is the governor of oyo state?",
choiceA : "Abiola Ajumobi",
choiceB : "Seyi makinde",
choiceC : "Alao Akala",
choiceD : "Green,Red,Green",
correct : "B"
},{
question : "What are the colors of the Nigerian Flag?",
choiceA : "Green,White,Blue",
choiceB : "Blue,White,Green",
choiceC : "Green,White,Green",
choiceD : "Green,Red,Green",
correct : "C"
}
];
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;
function continueAfterIntro(){
intro.style.display = 'none';
startt.style.display = 'block';
wel.innerHTML = `Hi ${name}`;
}
function renderQuestion(){
let q = questions[runningQuestion];
question.innerHTML = "<p>"+ q.question +"</p>";
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
}
function startQuiz(){
startt.style.display = "none";
quiz.style.display = "block";
renderQuestion();
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="quiz.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="container">
<div class="" id="introduction">
<div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
<div id="para1"><p>Hey there i'm AFO by name whats yours</p> </div>
<div id="name-button">
<span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
<span id="continue"><input type="button" value="Continue" id="continue"></span>
</div>
</div>
<div id="startt" style="display: none">
<p id="wel"></p>
<div id="start" >Start Quiz!</div>
</div>
<div id="quiz" style="display: none">
<div id="question"></div>
<div id="choices">
A.<div class="choice" id="A" onclick="checkAnswer('A')"></div>
B.<div class="choice" id="B" onclick="checkAnswer('B')"></div>
C.<div class="choice" id="C" onclick="checkAnswer('C')"></div>
D.<div class="choice" id="D" onclick="checkAnswer('D')"></div>
</div>
<div id="timer">
<div id="counter"></div>
<div id="btimeGauge"></div>
<div id="timeGauge"></div>
</div>
<div id="progress"></div>
</div>
<div id="scoreContainer" style="display: none"></div>
</div>
</body>
</html>
What ReferenceError mean MDN#ReferenceError

Categories