how to access the object in my array on function call - javascript

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

Related

movieReviewsApp: How to get the value (actual written text) from an input into a variable and display it somewhere else?

I made a html/javaScript app that get movie data from an API and displays it (index.html), when someone click the "see details" link from any movieCard theyre redirected to a new page (singleMovieView.html). I want to be able to write in an input/textarea, click a button and then, with createdElemenst of div, paragraps, h, etc, upload it into an empty div I made specially just for the reviews.
The singleMovieView.html display info of the particular movie and then, below, there are two divs; one for writing the review (textArea/input and button)and below that another div to display the pastReviews.
In theory the only thing thats missing is how to successfully put into the pastReviews div the just submitted review; I tried to do it just appendingElements to that div (pastReviews), but the html file crashes.
Heres the code:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Movies Site</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="topnav">
<a class="active" href="#">Movies Site</a>
<div class="search-container">
<form role="search" id="form">
<input type="search" id="query" name="q" placeholder="Search..">
</form>
</div>
</div>
<div style="padding-left:16px">
<section id="section"></section>
</body>
<script src="script.js"></script>
</html>
script.js:
const APILINK = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=41ee980e4b5f05f6693fda00eb7c4fd4&page=1';
const IMG_PATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?&api_key=41ee980e4b5f05f6693fda00eb7c4fd4&query=";
const main = document.getElementById("section");
const form = document.getElementById("form");
const search = document.getElementById("query");
const singleViewNameDiv = document.getElementById("movieNameSingleView");
returnMovies(APILINK)
function returnMovies(url)
{
fetch(url).then(res => res.json()).then
(function(data)
{
console.log(data.results);
data.results.forEach
(element =>
{
const div_card = document.createElement('div');
div_card.setAttribute('class', 'card');
const div_row = document.createElement('div');
div_row.setAttribute('class', 'row');
const div_column = document.createElement('div');
div_column.setAttribute('class', 'column');
const image = document.createElement('img');
image.setAttribute('class', 'thumbnail');
image.setAttribute('id', 'image');
image.setAttribute('width', 250);
const title = document.createElement('h3');
title.setAttribute('id', 'title');
const center = document.createElement('center');
title.innerHTML = `${element.title}`;
image.src = IMG_PATH + element.poster_path;
let oneTitle = `${element.title}`;
let twoImg = IMG_PATH + element.poster_path;
let threeOverview = element.overview;
let fourDate = element.release_date;
//////////////////////////////////////////////////////////////////////////////////
const aLink = document.createElement('a');
aLink.setAttribute('href', 'singleViewMovie.html?oneTitle=' + oneTitle + '&twoImg=' + twoImg + '&threeOverview=' + threeOverview + '&fourDate=' + fourDate); //+ '&lastValue=#');
aLink.innerText = 'Go to details';
//////////////////////////////////////////////////////////////////////////////////
center.appendChild(image);
div_card.appendChild(center);
div_card.appendChild(title);
div_card.appendChild(aLink);
div_column.appendChild(div_card);
div_row.appendChild(div_column);
main.appendChild(div_row);
}
);
}
);
}
form.addEventListener
("submit", (e) =>
{
e.preventDefault();
main.innerHTML = '';
const searchItem = search.value;
if (searchItem)
{
returnMovies(SEARCHAPI + searchItem);
search.value = "";
}
}
);
singleViewMovie.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replitSingleMovieView</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body style="background-color: #131720;">
<!--////////////////////"PRUEBA PARA VER CONTENIDO DE LOS PARAMETROS"////////////////////-->
<div id ="forTests">
</div>
<!--////////////////////"TITULO PARA REGRESAR A INDEX.HTML"////////////////////-->
<div>
<a href="index.html">
<h1>HOME</h1>
</a>
</div>
<!--////////////////////"NOMBRE DE LA PELICULA"////////////////////-->
<div id="movieNameSingleView">
</div>
<br/>
<!--////////////////////"IMAGEN DE LA PELICULA"////////////////////-->
<div id ="imageSingleView" style="background-color: #151f30; padding-left: 20px;">
</div>
<br/>
<br/>
<!--////////////////////"DETALLES DE LA PELICULA CON EL NOMBRE, FECHA Y DESCRIPCION"////////////////////-->
<div id="detailsSingleView">
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<!--////////////////////"DIV PARA HACER REVIEWS"////////////////////-->
<div>
<h3 style="color: white">MAKE A REVIEW:</h3>
<br/>
<form id="newReviewsContent">
<input type="text" placeholder="Review....." name="reviewBox" id="reviewBox"/>
</br>
<button onclick = "getText()">Add review</button>
</form>
</div>
<br/>
<br/>
<!--////////////////////"DIV MOSTRAR REVIEWS"////////////////////-->
<div>
<h3 style="color: white">PAST REVIEWS:</h3>
</br>
<div id="pastReviews">
</div>
</div>
<script src="singleView.js"></script>
</body>
<script src="singleView.js"></script>
</html>
singleView.js:
let stringTitle = window.location.href;
let stringImage = window.location.href;
let stringOverview = window.location.href;
let stringDate = window.location.href;
let indexStartOne = stringTitle.indexOf('oneTitle=');
indexStartOne += 9;
let indexStartTwoForOne = stringTitle.indexOf('twoImg=');
indexStartTwoForOne -= 1;
//////////"VARIABLE QUE CONTIENE EL NOMBRE DEL TITULO"//////////
///////////////////////////////////////////////////////////////
let titleName = stringTitle.slice(indexStartOne, indexStartTwoForOne);
let indexStartTwo = stringImage.indexOf('twoImg=');
indexStartTwo += 7;
let indexStartThreeForTwo = stringImage.indexOf('threeOverview=');
indexStartThreeForTwo -= 1;
//////////"VARIABLE QUE CONTIENE LA URL DE LA IMAGEN"////////////
////////////////////////////////////////////////////////////////
let imageUrl = stringImage.slice(indexStartTwo, indexStartThreeForTwo);
let indexStartThree = stringOverview.indexOf('threeOverview=');
indexStartThree += 14;
let indexStartFourForThree = stringOverview.indexOf('fourDate=');
indexStartFourForThree -= 1;
//////////"VARIABLE QUE CONTIENE LA DESCRIPCION DE LA PELICULA"////////////
//////////////////////////////////////////////////////////////////////////
let descriptionDetails = stringOverview.slice(indexStartThree, indexStartFourForThree);
let indexStartFour = stringDate.indexOf('fourDate=');
indexStartFour += 9;
//////////"VARIABLE QUE CONTIENE LA FECHA DE LA PELICULA"////////////
////////////////////////////////////////////////////////////////////
let dateFormat = stringDate.slice(indexStartFour);
const singleViewTitleDiv = document.getElementById("movieNameSingleView");
const singleViewImageDiv = document.getElementById("imageSingleView");
const singleViewDescriptionDiv = document.getElementById("detailsSingleView");
const titleElement = document.createElement('h2');
const imageElement = document.createElement('img');
const overviewElement = document.createElement('p');
const dateElement = document.createElement('p');
const breakElement = document.createElement('br');
titleElement.innerHTML = "MOVIE: " + titleName;
titleElement.setAttribute('style', 'color: white');
imageElement.src = imageUrl;
imageElement.setAttribute('width', 600);
overviewElement.innerHTML = descriptionDetails;
overviewElement.setAttribute('style', 'color: white');
dateElement.innerHTML = "RELEASE DATE: " + dateFormat;
dateElement.setAttribute('style', 'color: white');
singleViewTitleDiv.appendChild(titleElement);
singleViewImageDiv.appendChild(imageElement);
singleViewDescriptionDiv.appendChild(dateElement);
singleViewDescriptionDiv.appendChild(breakElement);
singleViewDescriptionDiv.appendChild(overviewElement);
function getText()
{
let reviewText = document.getElementById('reviewBox');
const showReviews = document.getElementById("pastReviews");
const pastReview = document.createElement('div');
const paragraphReview = document.createElement('p');
paragraphReview.innerHTML = reviewText;
pastReview.appendChild(paragraphReview);
showReviews.appendChild(pastReview);
}

html Text content not updating

I'm trying to make an incremental game. but when I test it out the game doesn't increment clicks, everything looks fine. So what am I doing wrong?
Thanks in advance :)
JavaScript Code(in separate file)
//Unused or copied code
// mass += energy;
// btn.innerText = mass + "mass";
//DOM
let btn = document.getElementById("btn");
let img = document.getElementById("img");
//Variables
var mass = 0;
var energy = 1;
var version = 0.1 + 'oab';
//El(s)
img.addEventListener('click', e => {
mass += energy;
let btn.textContent = mass + " Mass";
});
<input type="image" id="img" src="assets/sun.jpg" name="button" alt="clicker" width="250" height="250"><br>
<h1 id='btn'>0 Mass</h1>
There is no need to use let to assign .textContent
let btn = document.getElementById("btn");
let img = document.getElementById("img");
//Variables
var mass = 0;
var energy = 1;
var version = 0.1 + "oab";
//El(s)
img.addEventListener("click", (e) => {
mass += energy;
btn.textContent = mass + " Mass";
});
<input type="image" id="img" src="https://source.unsplash.com/random/" name="button" alt="clicker" width="400" height="100" />
<br />
<h1 id="btn">0 Mass</h1>
#ManasKhandelwal
HTML code:
<body>
<h1 id="btn">0 Mass</h1>
<h1 id="nrg">1 Energy</h1>
<br><br><br>
<input type="image" id="img" src="assets/sun.jpg" name="img" alt="clicker" width="250" height="250">
<br><br>
<div id="spacerock">
<h1>Space Rock</h1>
<div id="rest">
<img src="assets/space_rock.png" alt="space rock" width="32" height="30">
<div id="l&c">
<h2>Cost: 50</h2>
<h2>LvL: 1</h2>
</div>
</div>
</div>
<script src ="js/main.js"></script>
</body>
</html>
Javascript Code:
img.addEventListener('click', (e) => {
mass += sra;
btn.innerHTML = mass + ' Mass';
});
spaceRock.addEventListener('click', (e) => {
if (mass >= srp) {
if (srl <= 12) {
energy += sra;
srl += 1;
srp = srl * 50;
sra += 1.5;
nrg.innerHTML = energy;
} else {
nrg.innerHTML = 'MAX';
}
}
});
const text = document.innerHTML();
const btn = document.querySelector('btn');
const img = document.querySelector('img');
const nrg = document.querySelector('nrg');
const spaceRock = document.querySelector('spacerock');

calculate total score using javascript

I am creating a quiz. My quiz is divided in 4 parts and I have 50 questions total. There is a score and question counter, but I want to continue the question counter and score when the quiz jumped to the next part and I need a total score at the end. I am not expert in Javascript. I am just a beginner. So Please help me with the solution.
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progressText");
const scoreText = document.getElementById("score");
const progressBarFull = document.getElementById("progressBarFull");
let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuesions = [];
let questions = [
{
question: "Inside which HTML element do we put the JavaScript??",
choice1: "<script>",
choice2: "<javascript>",
choice3: "<js>",
choice4: "<scripting>",
answer: 1
},
{
question:
"What is the correct syntax for referring to an external script called 'xxx.js'?",
choice1: "<script href='xxx.js'>",
choice2: "<script name='xxx.js'>",
choice3: "<script src='xxx.js'>",
choice4: "<script file='xxx.js'>",
answer: 3
},
{
question: " How do you write 'Hello World' in an alert box?",
choice1: "msgBox('Hello World');",
choice2: "alertBox('Hello World');",
choice3: "msg('Hello World');",
choice4: "alert('Hello World');",
answer: 4
}
];
//CONSTANTS
const CORRECT_BONUS = 10;
const MAX_QUESTIONS = 3;
startGame = () => {
questionCounter = 0;
score = 0;
availableQuesions = [...questions];
getNewQuestion();
};
getNewQuestion = () => {
if (availableQuesions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem("mostRecentScore", score);
//go to the end page
return window.location.assign("/end.html");
}
questionCounter++;
progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`;
//Update the progress bar
progressBarFull.style.width = `${(questionCounter / MAX_QUESTIONS) * 100}%`;
const questionIndex = Math.floor(Math.random() * availableQuesions.length);
currentQuestion = availableQuesions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach(choice => {
const number = choice.dataset["number"];
choice.innerText = currentQuestion["choice" + number];
});
availableQuesions.splice(questionIndex, 1);
acceptingAnswers = true;
};
choices.forEach(choice => {
choice.addEventListener("click", e => {
if (!acceptingAnswers) return;
acceptingAnswers = false;
const selectedChoice = e.target;
const selectedAnswer = selectedChoice.dataset["number"];
const classToApply =
selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
if (classToApply === "correct") {
incrementScore(CORRECT_BONUS);
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout(() => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
});
});
incrementScore = num => {
score += num;
scoreText.innerText = score;
};
startGame();
<html lang="en">
<head>
<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>Quick Quiz - Play</title>
<link rel="stylesheet" href="app.css" />
<link rel="stylesheet" href="game.css" />
</head>
<body>
<div class="container">
<div id="game" class="justify-center flex-column">
<div id="hud">
<div id="hud-item">
<p id="progressText" class="hud-prefix">
Question
</p>
<div id="progressBar">
<div id="progressBarFull"></div>
</div>
</div>
<div id="hud-item">
<p class="hud-prefix">
Score
</p>
<h1 class="hud-main-text" id="score">
0
</h1>
</div>
</div>
<h2 id="question">What is the answer to this questions?</h2>
<div class="choice-container">
<p class="choice-prefix">A</p>
<p class="choice-text" data-number="1">Choice 1</p>
</div>
<div class="choice-container">
<p class="choice-prefix">B</p>
<p class="choice-text" data-number="2">Choice 2</p>
</div>
<div class="choice-container">
<p class="choice-prefix">C</p>
<p class="choice-text" data-number="3">Choice 3</p>
</div>
<div class="choice-container">
<p class="choice-prefix">D</p>
<p class="choice-text" data-number="4">Choice 4</p>
</div>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
If your quiz contains or lasts throughout multiple pages and you want to communicate between those pages then you can use localStorage
When you're done with one part of the quiz, or even if you're not, just set the value of localStorage to the score, and read it on page load, or in general
incrementScore = num => {
if(typeof(localStorage.getItem("score") != "number"))
localStorage.setItem("score", 0)
score = localStorage.getItem("score")
score += num;
scoreText.innerText = score;
};

Calculation not working when value with comma

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>

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")
//}

Categories