Back button not remembering choices in Javascript quiz - javascript

I need help on the following code, I created a back button in my Javascript Quiz, but if I click on it, it goes back but does not remember the choices i chose thereby forcing me to choose a new answer. I don't know how to go about this. Below is the Javascript Link:
http://jsbin.com/zinagipovo/edit?html,css,js,console
var currentQuestion = 0;
var score = 0;
var totQuestions = questions.length;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var backButton = document.getElementById('backButton');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
function loadQuestion (questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex + 1) + '. ' +q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;
};
function loadNextQuestion () {
var selectedOption =
document.querySelector('input[type=radio]:checked');
if(!selectedOption){
alert('Please select your answer!');
return;
}
var answer = selectedOption.value;
if(questions[currentQuestion].answer == answer){
score +=1;
}
selectedOption.checked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1){
nextButton.textContent = 'Finish';
}
if (currentQuestion == totQuestions){
resultCont.style.display = '';
resultCont.textContent = 'You got ' + score +' questions correct';
return false;
currentQuestion = 0;
}
loadQuestion(currentQuestion);
}
function loadPrevQuestion () {
if (currentQuestion > 0) {
currentQuestion--;
loadQuestion(currentQuestion);
}
}
loadQuestion(currentQuestion);
The questions are in an external file
var questions = [{
"question": "How many long vowels do we have in English Language?",
"option1": "10",
"option2": "5",
"option3": "6",
"option4": "7",
"answer": "2"
}, {
"question": "How many short vowels do we have in English Language?",
"option1": "6",
"option2": "5",
"option3": "12",
"option4": "7",
"answer": "4"
}, {
"question": "How many Vowels do we have in English Language?",
"option1": "20",
"option2": "24",
"option3": "8",
"option4": "12",
"answer": "1"
}, {
"question":"Which of these is not a Vowel Sound?",
"option1": "/θ/",
"option2": "/əʊ/",
"option3": "/i:/",
"option4": "/u:/",
"answer": "1"
},
]
The HTML Code goes thus:
<div>
<button id="quiz" onclick="document.getElementById('quizContainer').style.display='block'" style="width:auto; margin-top: 15px;">Take the Quiz!!</button>
<div id="quizContainer" class="modal">
<span onclick="document.getElementById('quizContainer').style.display='none'" class="close" title="Close Quiz">×</span>
<header class="title">Vowel Sounds</header>
<div id="question" class="question"></div>
<label class="option"><input type="radio" name="option" value="1" /> <span id="opt1"></span></label>
<label class="option"><input type="radio" name="option" value="2" /> <span id="opt2"></span></label>
<label class="option"><input type="radio" name="option" value="3" /> <span id="opt3"></span></label>
<label class="option"><input type="radio" name="option" value="4" /> <span id="opt4"></span></label>
<button id="nextButton" class="next-btn" onclick="loadNextQuestion();">Next</button>
<button id="backButton" class="back-btn" onclick="loadPrevQuestion();">Back</button>
<div id="result" class="container result" style="display:none;"></div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('quizContainer');
</script>
The CSS code is:
.modal { display: none; background-color: #fefefe; height: 387px; width: 100%; position: fixed; z-index: 1; overflow: auto; padding-top: 100px; margin-top: 100px; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); padding: 20px; border: 1px solid #08038C; box-shadow: 0 0 8px 3px #fff; }
.title { padding-top: 20px; text-align: center; font-size: 40px; text-transform: uppercase; color: #08038c; }
.question { padding: 20px; font-size: 22px; background: #08038c; border-radius: 20px; margin: 10px 0 10px 0; color: #f6f6f6; }
.option{ width: 450px; display: inline-block; padding: 10px 0 10px 15px; vertical-align: middle; background: #08038c; margin: 10px 0 10px 10px; color: white; border-radius: 20px; }
.option:hover{ background: #08038c; color: #f6f6f6;}
.next-btn, .back-btn { border: 2px solid #08038c; outline: none; background: rgba(255,255,255, 0.5); width: 150px; height: 35px; cursor: pointer; float: right; margin: 10px; }
.next-btn:hover, .back-btn:hover { background: #08038c; color: #f6f6f6; }
.result { height: 20px; text-align: center; font-size: 20px; }
.option input:checked .option{ background: #08038c; color: #000; }
.close { position: absolute; right: 35px; top: 15px; color: #000; font-size: 40px; font-weight: bold; }
#quiz { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; }
.back-btn { float:left;}
.close:hover, .close:focus { color: red; cursor: pointer; }

You have a typo in the jsbin's JavaScript. You define totQuestions before you define questions. If you move it to after your program at least runs.
The general idea should be to store the answers and calculate the total at the end. You can simply create another array, answers, and in loadNextQuestion, set answers[currentQuestion] = answer instead of your if/score += 1 block. You can add similar functionality to loadPrevQuestion. Then in loadQuestion, you would set checked of the option corresponding to answers[currentQuestion]. Finally, instead of the score variable, you'd calculate it at the end, such as by a reduction.
Here's a jsbin doing the above, though it's using ES6 and instead of an answers array I melded it into questions and made the options dynamic.

Related

My JS code is not working and the content of my two-question form is not displaying inside the central div. Could someone please fix my JS code?

Could someone please correct my JS code and tell me what was done in order to do so? I was wondering what did I do wrongly that leads my quiz questions and its alternatives to be not displayable inside the central div.
Contextualising my code: it is a two-questions form and the results of it should be displayed at the top of the page in the afterwards of a click in the Evaluate button, however my focus for now is to understand how one can make the quiz visible in the HTML/CSS page.
Link to CodePen: My code snippet
const quizQuestions = {
questions = {
question: "What is the of the state of Pará?",
alternatives: {
0: "São Paulo",
1: "Guarulhos",
2: "Campinas",
3: "São Bernardo do Campo",
4: "São José dos Campos",
5: "Santo André",
6: "Ribeirão Preto",
7: "Belém",
answer: "7"
},
{
question: "What is the capital of the state of Amapá?",
alternatives: {
0: "Osasco",
1: "Sorocaba",
2: "Mauá",
3: "Macapá",
4 "São José do Rio Preto",
5: "Mogi das Cruzes",
6: "Santos",
answer: "3"
};
document.getElementByClassName('.quiz-container ').addEventListener('click', function() {
let container =
document.querySelector('.quiz-container');
container.innerHTML = '<div class="quiz-container"></div>';
for (const [key, value] of Object.entries(quizQuestion.alternatives)) {
container.innerHTML += `<input type="radio" name="choice" value="${key}"> ${value}`;
}
container.innerHTML += '<div><button type="submit" id="submit-button">Evaluate</button></div>';
document.getElementById('submit2').addEventListener('click', function(event) {
console.log('asdf');
event.preventDefault();
var selected = document.querySelector('input[type="radio"]:checked');
if (selected && selected.value == quizQuestion.answer) {
alert('It is super, super correct :D!');
} else {
alert('Unfortunately, it is incorrect :(!');
}
});
});
body {
background: rgb(209, 29, 83);
margin: 0;
}
h1 {
background: rgb(255, 184, 201);
height: 60px;
margin: 0;
padding-left: 20px;
padding-top: 20px;
font-size: 45px;
text-shadow: 3px 3px 9px;
color: rgb(43, 29, 14);
}
.quiz-container {
text-align: left;
font-size: 25px;
background: rgb(255, 209, 220);
width: 700px;
height: 4000px;
margin: auto;
margin-top: 100px;
box-shadow: 9px 9px 10px;
margin-bottom: 60px;
}
button {
margin-left: 900px;
padding-top: 0;
margin-bottom: 60px;
}
.questions {
color: #000000;
text-align: center;
font-size: 15px;
}
<head>
<h1>QUIZ centred in Brazil</h1>
</head>
<body>
<div class="quiz-container"></div>
<div>
<button type="submit" id="submit-button">Evaluate</button>
</div>
<script src="js/main.js"></script>
</body>
There's a lot of issues in your code.
The first issue is your quizQuestions are structured wrong. They should be an array of objects, each containing a question, an array of alternatives, and an answer - I have corrected it in the snippet.
The second issue is with how you get the element - unique elements need to have unique ids don't use classes like that - which is why document.getElementByClassName does not exist, because it would be document.getElementsByClassName since classes are not unique like ids are. You also have a ., which is correct for a css selector or for jquery, but is not used in this form of getting - I updated it to use an id, correcting your css to match.
I am not sure how you were trying to do some of what you were doing, but this should be a workable starting point to get you moving again - I didn't include the question checking portion, since this was enough to get the box filled as you asked for.
const quizQuestions = [{
question: "What is the of the state of Pará?",
alternatives: [
"São Paulo",
"Guarulhos",
"Campinas",
"São Bernardo do Campo",
"São José dos Campos",
"Santo André",
"Ribeirão Preto",
"Belém"
],
answer:7
},{
question: "What is the capital of the state of Amapá?",
alternatives: [
"Osasco",
"Sorocaba",
"Mauá",
"Macapá",
"São José do Rio Preto",
"Mogi das Cruzes",
"Santos"
],
answer:3
}];
window.onload = function (){
const container = document.getElementById('quiz-container');
quizQuestions.forEach((question, number) => {
let questionHTML = `<div class="question"><h3>${question.question}</h3>`;
question.alternatives.forEach((value, key) => {
questionHTML += `<input type="radio" name="${number}choice" value="${key}">${value}<br />`;
});
questionHTML += "</div>";
container.innerHTML += questionHTML;
});
};
body {
background: rgb(209, 29, 83);
margin: 0;
}
h1 {
background: rgb(255, 184, 201);
height: 60px;
margin: 0;
padding-left: 20px;
padding-top: 20px;
font-size: 45px;
text-shadow: 3px 3px 9px;
color: rgb(43, 29, 14);
}
#quiz-container {
text-align: left;
font-size: 25px;
background: rgb(255, 209, 220);
width: 700px;
height: 4000px;
margin: auto;
margin-top: 100px;
box-shadow: 9px 9px 10px;
margin-bottom: 60px;
}
button {
margin-left: 900px;
padding-top: 0;
margin-bottom: 60px;
}
.question {
color: #000000;
text-align: center;
font-size: 15px;
}
<head>
<h1>QUIZ centred in Brazil</h1>
</head>
<body>
<div id="quiz-container"></div>
<div>
<button type="submit" id="submit-button">Evaluate</button>
</div>
<script src="js/main.js"></script>
</body>

Issues with quiz logging correct answer and issues with answer highlighting green

I am new to coding and I am having a few issues with my quiz app. For one, after altering my code with adding radio buttons, my quiz for some reason no longer logs the correct answer and the score remains 0. Also, I would like to keep it in the same for
const myQuestions = [{
'question': 'WHAT IS THE OFFICE AWARDS NIGHT CALLED?',
'answers': ["DORKIES", "DUNDIES", "DWEEBIES", "DINGLES"],
'correct': 1
},
{
'question': 'WHAT IS THE GIANT POT THAT KEVIN DROPS ALL OVER THE OFFICE FLOOR?',
'answers': ["GRAVY", "SOUP", "MAC & CHEESE", "CHILI"],
'correct': 3
},
{
'question': "HOW LONG HAD JIM AND PAM BEEN DATING BEFORE HE BOUGHT HER ENGAGEMENT RING",
'answers': ["ONE WEEK", "ONE MONTH", "ONE YEAR", "TWO YEARS"],
'correct': 0
},
{
'question': "WHAT DOES MICHAEL CHOOSE AS HIS USERNAME WHEN HE SIGNS UP FOR AN ONLINE DATING SITE?",
'answers': ["LITTLEKIDLOVER", "IAMTHEBOSS", "DUNDERMIFF", "READYFORMARRIAGE"],
'correct': 0
},
{
'question': "WHAT IS ERIN'S REAL FIRST NAME?",
'answers': ["BRITTANY", "CHRISTINE", "BECCA", "KELLY"],
'correct': 3
},
{
'question': "WHICH COUNTRY DOES TOBY MOVE TO WHEN HE LEAVES HIS JOB AT DUNDER MIFLIN ONLY TO RETURN LATER?",
'answers': ["JAMAICA", "COSTA RICA", "ITALY", "CUBA"],
'correct': 1
},
{
'question': "DWIGHT AND ANDY HAVE A DUEL OVER WHICH WOMAN IN THE OFFICE?",
'answers': ["ANGELA", "ERIN", "KELLY", "MEREDITH"],
'correct': 0
},
{
'question': "WHAT IS THE NAME OF THE CAT THAT ANGELA THROWS AT OSCAR DURING THE FIRE DRILL?",
'answers': ["SPRINKLES", "CUPCAKE", "BANDIT", "TINKERBELL"],
'correct': 2
},
{
'question': "WHAT DOES JAN NAME THE BABY SHE HAS VIA SPERM DONOR?",
'answers': ["AXON", "ALLY", "APPLE", "ASTRID"],
'correct': 3
},
{
'question': "HOW MANY KIDS DO PAM AND JIM HAVE?",
'answers': ["3", "2", "1", "0"],
'correct': 1
}];
let score = 0;
let current = 0;
$(document).ready(function() {
// start button event listener
$(".start-button").click(function() {
$('.start-page').hide();
$('.next').hide();
$('.questions').show();
displayQuestion();
$('.score').text('Current Score: ' + score);
console.log("Start Quiz button clicked");
});
// next button event listener
$(".next-button").click(function(event) {
console.log("Next button clicked");
displayQuestion();
$('.next').hide();
$('.submit').show();
});
$(".submit-button").click(function(event) {
event.preventDefault();
var selected = $('input.selected');
console.log(event);
if (selected.length) {
let answer = $('input.selected').attr('id');
console.log(answer);
checkAnswer(answer);
console.log("hey world");
$('.next').show();
$('.submit').hide();
} else {
alert('Please select an answer');
}
});
// retry button click listener
$(".retry-button").click(function() {
location.reload();
console.log("Retake button clicked");
});
//click listener to make questions change color on hover
$('div.questions-selector').on('click', 'input', function(event) {
$('.selected').removeClass();
$(this).addClass('selected');
});
});
//FUNCTIONS
function displayQuestion() {
$('.question-number').text('Question Number: ' + (current + 1) + "/10");
if (current < myQuestions.length) {
let listQuestion = myQuestions[current];
$('h2').text(listQuestion.question);
$('div.questions-selector').html('');
for (let i = 0; i < listQuestion.answers.length; i++) {
$('div.questions-selector').append(`<div><label
for"input${i}">${listQuestion.answers[i]}</label>
<input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
}
} else {
// show summary that says how many you got correct
displayScore();
}
}
// function stub to check answer
function checkAnswer(answer) {
let listQuestion = myQuestions[current];
if (listQuestion.correct == answer) {
score++;
$('label.selected').addClass('correct');
} else {
$('label.selected').addClass('incorrect');
}
$('.score').text('Current Score: ' + score);
current++;
}
//function to display score
function displayScore() {
$('.questions').hide();
$('.end-quiz').show();
$('.end-score').text("Your score: " + score + '/10');
if (score >= 7) {
$('.comment').text('Nice job, Superfan!');
} else {
$('.comment').text('Get to binge watching and try again!')
}
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #586060;
background-repeat: no-repeat;
background-size: cover;
font-family: 'Mina', sans-serif;
color: white;
font-size: 20px;
margin: 10px;
}
.topbar {
max-width: 800px;
margin-top: 20px;
font-size: 12px;
padding-bottom: 30px;
font-weight: bold;
color: white;
}
h1,
h2 {
text-align: center;
font-weight: bold;
color: white;
display: block;
}
h2 {
font-size: 20px;
color: white;
display: block;
}
button {
width: 300px;
height: 40px;
background: #d4f4dd;
font-family: 'Mina', sans-serif;
font-size: 20px;
font-weight: 300;
color: #424b54;
border: 2px solid #d4f4dd;
}
.start-page {
width: 500px;
height: 300px;
margin: 10px auto;
text-align: center;
padding-bottom: 200px;
color: white;
}
.questions,
.end-quiz {
display: none;
text-align: center;
padding-bottom: 0px;
margin: 0 auto 0 auto;
text-align: center;
width: 500px;
height: 300px;
min-height: 300px;
}
.end-quiz {
padding-top: 80px;
height: 100px;
font-size: 30px;
color: white;
}
.question-number,
.score {
font-size: 30px;
color: white;
padding-top: 0px;
}
.div {
list-style: none;
padding: 0;
}
.input {
border: 1px solid #d6d6cf;
width: 200px;
margin: 5px auto;
font-size: 18px;
border-radius: 5px;
padding: 5px;
}
.selected {
background: #f2b632;
color: #252839;
}
.correct {
background-color: lightgreen;
}
.incorrect {
background-color: red;
}
#media screen and (min-width: 300px) {
.topbar {
width: 50%;
margin: auto;
padding-top: 30px;
font-size: 20px;
}
.questions .end-quiz {
width: 200px;
margin: 0 auto;
}
}
#media screen and (min-width: 600px) {
.topbar {
width: 80%;
font-size: 40px;
margin: 0 auto;
}
.questions .end-quiz {
width: 400px;
margin: 0 auto;
}
}
#media screen and (max-width: 900px) {
.topbar {
font-size: 60px;
font-weight: bold;
margin: 0 auto;
}
}
.questions .end-quiz {
width: 600px;
margin: 0 auto;
}
}
fieldset {
min-height: 300px;
}
}
.label {
display: block;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<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">
<link rel="stylesheet" href="./float-grid.css" />
<link rel="stylesheet" href="index.css">
<link href="https://fonts.googleapis.com/css?family=Mina"
rel="stylesheet">
<title>Quiz App</title>
</head>
<body>
<main>
<!--Section 1 WELCOME-->
<h1 class="topbar"><marquee behavior="alternate">The Office
Quiz</marquee></h1>
<div class="start-page">
<p>Are you a true fan of The Office? Let's find out!</p>
<button value="start" type="start" class="start-button">Begin
Quiz</button>
</div>
<!--Section 2 QUESTIONS-->
<form class="questions">
<fieldset>
<Legend>
<h2 class="question"></h2></Legend>
<div class="questions-selector"></div>
<div class="submit">
<button value="submit" type="submit" class="submit-button">Check
Your Answer</button>
</div>
</fieldset>
</form>
<div class="questions">
<div class="next">
<button value="next" type="next" class="next-button">Next
Question</button>
</div>
<p class="score">Score:</p>
<p class="question-number"></p>
</div>
<!--SECTION 3 RESULTS-->
<section class='end-quiz'>
<p class='end-score'></p>
<p class='comment'></p>
<button value="retry" type="retry" class="retry-button">Retake
Quiz</button>
</section>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
mat, however, I do not want buttons because I would like it to highlight the correct answer green.
You have a little mess in your code, and I am not proud of my improvement but I've made changes and code is working again. Look on my changes:
In function displayQuestions I've added new attribute to radio button (ans)
<input type="radio" **ans=${i}** name="choice" value="0" id = "input${i}">
</input></div>`)
$(.submit-button) I've added quest variable and I've changed answer variable
$(".submit-button").click(function(event) {
event.preventDefault();
var selected = $('input.selected');
if (selected.length) {
**let answer = $('input.selected').attr('ans');**
**let quest = $('input.selected').attr('id');**
**checkAnswer(answer,quest);**
$('.next').show();
$('.submit').hide();
} else {
alert('Please select an answer');
}
});
I've changed checkAnswer function
function checkAnswer(answer,question) {
let listQuestion = myQuestions[current];
if (listQuestion.correct === Number.parseInt(answer)) {
score++;
document.getElementById(question).previousElementSibling.classList.add('correct');
} else {
document.getElementById(question).previousElementSibling.classList.add('incorrect')
}
$('.score').text('Current Score: ' + score);
current++;
}
I hope this will help you. Good luck!
There is something missed in this function.
function displayQuestion() {
$('.question-number').text('Question Number: ' + (current + 1) + "/10");
if (current < myQuestions.length) {
let listQuestion = myQuestions[current];
$('h2').text(listQuestion.question);
$('div.questions-selector').html('');
for (let i = 0; i < listQuestion.answers.length; i++) {
$('div.questions-selector').append(`<div><label
for"input${i}">${listQuestion.answers[i]}</label>
<input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
}
} else {
// show summary that says how many you got correct
displayScore();
}
}
You should fix this part.
<input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
this input${i} is the reason you can't get the correct answer. Simply modify your code to be like this.
<input type="radio" name="choice" value="0" id = "${i}"></input></div>`)
You got close, but a couple things you missed:
You are styling (through your classes) your input and not your selected label with your jQuery process, which makes the background changes hard to see
In your checkAnswerfunction you're actually not comparing the two same things, which results in bad conditionnal test
See your code revised for something working (note it is styling the div and not the label, I let you work this out). You can search for MODIFICATIONS BELOW tag to see where I touched it.
const myQuestions = [{
'question': 'WHAT IS THE OFFICE AWARDS NIGHT CALLED?',
'answers': ["DORKIES", "DUNDIES", "DWEEBIES", "DINGLES"],
'correct': 1
},
{
'question': 'WHAT IS THE GIANT POT THAT KEVIN DROPS ALL OVER THE OFFICE FLOOR?',
'answers': ["GRAVY", "SOUP", "MAC & CHEESE", "CHILI"],
'correct': 3
},
{
'question': "HOW LONG HAD JIM AND PAM BEEN DATING BEFORE HE BOUGHT HER ENGAGEMENT RING",
'answers': ["ONE WEEK", "ONE MONTH", "ONE YEAR", "TWO YEARS"],
'correct': 0
},
{
'question': "WHAT DOES MICHAEL CHOOSE AS HIS USERNAME WHEN HE SIGNS UP FOR AN ONLINE DATING SITE?",
'answers': ["LITTLEKIDLOVER", "IAMTHEBOSS", "DUNDERMIFF", "READYFORMARRIAGE"],
'correct': 0
},
{
'question': "WHAT IS ERIN'S REAL FIRST NAME?",
'answers': ["BRITTANY", "CHRISTINE", "BECCA", "KELLY"],
'correct': 3
},
{
'question': "WHICH COUNTRY DOES TOBY MOVE TO WHEN HE LEAVES HIS JOB AT DUNDER MIFLIN ONLY TO RETURN LATER?",
'answers': ["JAMAICA", "COSTA RICA", "ITALY", "CUBA"],
'correct': 1
},
{
'question': "DWIGHT AND ANDY HAVE A DUEL OVER WHICH WOMAN IN THE OFFICE?",
'answers': ["ANGELA", "ERIN", "KELLY", "MEREDITH"],
'correct': 0
},
{
'question': "WHAT IS THE NAME OF THE CAT THAT ANGELA THROWS AT OSCAR DURING THE FIRE DRILL?",
'answers': ["SPRINKLES", "CUPCAKE", "BANDIT", "TINKERBELL"],
'correct': 2
},
{
'question': "WHAT DOES JAN NAME THE BABY SHE HAS VIA SPERM DONOR?",
'answers': ["AXON", "ALLY", "APPLE", "ASTRID"],
'correct': 3
},
{
'question': "HOW MANY KIDS DO PAM AND JIM HAVE?",
'answers': ["3", "2", "1", "0"],
'correct': 1
}];
let score = 0;
let current = 0;
$(document).ready(function() {
// start button event listener
$(".start-button").click(function() {
$('.start-page').hide();
$('.next').hide();
$('.questions').show();
displayQuestion();
$('.score').text('Current Score: ' + score);
console.log("Start Quiz button clicked");
});
// next button event listener
$(".next-button").click(function(event) {
console.log("Next button clicked");
displayQuestion();
$('.next').hide();
$('.submit').show();
});
$(".submit-button").click(function(event) {
event.preventDefault();
var selected = $('input.selected');
//console.log(event);
if (selected.length) {
let answer = $('input.selected').attr('id');
console.log("answer: " + answer);
checkAnswer(answer);
$('.next').show();
$('.submit').hide();
} else {
alert('Please select an answer');
}
});
// retry button click listener
$(".retry-button").click(function() {
location.reload();
console.log("Retake button clicked");
});
//click listener to make questions change color on hover
$('div.questions-selector').on('click', 'input', function(event) {
$('.selected').removeClass();
$(this).addClass('selected');
// MODIFICATIONS BELOW
$(this).parent().addClass('selected');
});
});
//FUNCTIONS
function displayQuestion() {
$('.question-number').text('Question Number: ' + (current + 1) + "/10");
if (current < myQuestions.length) {
let listQuestion = myQuestions[current];
$('h2').text(listQuestion.question);
$('div.questions-selector').html('');
for (let i = 0; i < listQuestion.answers.length; i++) {
$('div.questions-selector').append(`<div><label
for"input${i}">${listQuestion.answers[i]}</label>
<input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
}
} else {
// show summary that says how many you got correct
displayScore();
}
}
// function stub to check answer
function checkAnswer(answer) {
let listQuestion = myQuestions[current];
// MODIFICATIONS BELOW
const inputString = "input";
const correctId = inputString.concat(listQuestion.correct);
console.log("correctId: " + correctId);
if (correctId == answer) {
score++;
} else {
$('#'+answer).parent().addClass('incorrect');
}
$('#'+correctId).parent().addClass('correct');
$('.score').text('Current Score: ' + score);
current++;
}
//function to display score
function displayScore() {
$('.questions').hide();
$('.end-quiz').show();
$('.end-score').text("Your score: " + score + '/10');
if (score >= 7) {
$('.comment').text('Nice job, Superfan!');
} else {
$('.comment').text('Get to binge watching and try again!')
}
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #586060;
background-repeat: no-repeat;
background-size: cover;
font-family: 'Mina', sans-serif;
color: white;
font-size: 20px;
margin: 10px;
}
.topbar {
max-width: 800px;
margin-top: 20px;
font-size: 12px;
padding-bottom: 30px;
font-weight: bold;
color: white;
}
h1,
h2 {
text-align: center;
font-weight: bold;
color: white;
display: block;
}
h2 {
font-size: 20px;
color: white;
display: block;
}
button {
width: 300px;
height: 40px;
background: #d4f4dd;
font-family: 'Mina', sans-serif;
font-size: 20px;
font-weight: 300;
color: #424b54;
border: 2px solid #d4f4dd;
}
.start-page {
width: 500px;
height: 300px;
margin: 10px auto;
text-align: center;
padding-bottom: 200px;
color: white;
}
.questions,
.end-quiz {
display: none;
text-align: center;
padding-bottom: 0px;
margin: 0 auto 0 auto;
text-align: center;
width: 500px;
height: 300px;
min-height: 300px;
}
.end-quiz {
padding-top: 80px;
height: 100px;
font-size: 30px;
color: white;
}
.question-number,
.score {
font-size: 30px;
color: white;
padding-top: 0px;
}
.div {
list-style: none;
padding: 0;
}
.input {
border: 1px solid #d6d6cf;
width: 200px;
margin: 5px auto;
font-size: 18px;
border-radius: 5px;
padding: 5px;
}
.selected {
background: #f2b632;
color: #252839;
}
div.correct {
background-color: lightgreen;
}
div.incorrect {
background-color: red;
}
#media screen and (min-width: 300px) {
.topbar {
width: 50%;
margin: auto;
padding-top: 30px;
font-size: 20px;
}
.questions .end-quiz {
width: 200px;
margin: 0 auto;
}
}
#media screen and (min-width: 600px) {
.topbar {
width: 80%;
font-size: 40px;
margin: 0 auto;
}
.questions .end-quiz {
width: 400px;
margin: 0 auto;
}
}
#media screen and (max-width: 900px) {
.topbar {
font-size: 60px;
font-weight: bold;
margin: 0 auto;
}
}
.questions .end-quiz {
width: 600px;
margin: 0 auto;
}
}
fieldset {
min-height: 300px;
}
}
.label {
display: block;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<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">
<link rel="stylesheet" href="./float-grid.css" />
<link rel="stylesheet" href="index.css">
<link href="https://fonts.googleapis.com/css?family=Mina"
rel="stylesheet">
<title>Quiz App</title>
</head>
<body>
<main>
<!--Section 1 WELCOME-->
<h1 class="topbar"><marquee behavior="alternate">The Office
Quiz</marquee></h1>
<div class="start-page">
<p>Are you a true fan of The Office? Let's find out!</p>
<button value="start" type="start" class="start-button">Begin
Quiz</button>
</div>
<!--Section 2 QUESTIONS-->
<form class="questions">
<fieldset>
<Legend>
<h2 class="question"></h2></Legend>
<div class="questions-selector"></div>
<div class="submit">
<button value="submit" type="submit" class="submit-button">Check
Your Answer</button>
</div>
</fieldset>
</form>
<div class="questions">
<div class="next">
<button value="next" type="next" class="next-button">Next
Question</button>
</div>
<p class="score">Score:</p>
<p class="question-number"></p>
</div>
<!--SECTION 3 RESULTS-->
<section class='end-quiz'>
<p class='end-score'></p>
<p class='comment'></p>
<button value="retry" type="retry" class="retry-button">Retake
Quiz</button>
</section>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>

Quiz , want to show both correct and incorrect answer when the choosen answer is incorrect

Need to get the green background on the correct answer with the red background on the incorrect answer when we choose a wrong answer in the quiz
const myQuestions = [
{
'question': 'What is the Full-form of GST?',
'answers': ["Good and Supply Tax","Goods and Services Tax","Good and Service Tax","Great Service Tax"],
'correct': 1
},
{
'question': 'Upper limit on investment in Kisan Vikas Patra (KVP)?',
'answers': ["5000", "10000", "50000", "25000"],
'correct': 0
},
{
'question': "Which insurance company has come up with India's first ever insurance cover for individual victims of cyber crime?",
'answers': ["ICICI","Muthoot Finance","LIC","Bajaj Allianz"],
'correct': 2
},
{
'question': "How much amount will be provided by NITI Aayog to every district to encourage digital payment system?",
'answers': ["Rs 1 lakh","Rs 2 lakh","Rs 5 lakh","Rs 10 lakh"],
'correct': 2
},
{
'question': "What company was the first company to produce a handheld mobile phone?",
'answers': ["Motorola", "Nokia", "Samsung" , "Apple"],
'correct': 0
},
{
'question': "What was the first version of Windows?",
'answers': ["Windows 95","Windows 7","Windows 1.01","Windows NT 3"],
'correct': 2
},
{
'question':"Who is the founder of Amazon?",
'answers': ["John Mackey", "Jeff Bezos", "Lee Byung-chul", "Howard Shultz"],
'correct': 1
},
{
'question':"When was Amazon founded?",
'answers': ["2005", "2002", "1996", "1994"],
'correct': 3
},
{
'question':"What does the internet prefix WWW stand for?",
'answers': ["Western Web World", "World Wide Web", "World Wide World", "We Wide Web"],
'correct': 1
},
{
'question': "What is the most used web browser in 2017?",
'answers': ["Safari","Internet Explorer","Chrome", "Firefox"],
'correct': 2
}
];
var score = 0;
var current = 0;
$(document).ready(function(){
// Create an event listener to listen for a click on the Start Quiz button
$(".start-button").click(function(){
$('.start-quiz').hide();
$('.next').hide();
$('.questions').show();
displayQuestion();
$('.score').text('Current Score: '+score);
console.log("Start Quiz button clicked");
});
// Create an event listener to listen for a click on the Next button
$(".next-button").click(function(event){
console.log("Next button clicked");
displayQuestion();
$('.next').hide();
$('.submit').show();
});
$(".submit-button").click(function(event){
if($('li.selected').length){
var answer = $('li.selected').attr('id');
checkAnswer(answer);
$('.next').show();
$('.submit').hide();
} else {
alert('Please select an answer');
}
});
// Create an event listener to listen for a click on the Retake button and refresh the page
$(".retake-button").click(function(){
location.reload();
console.log("Retake button clicked");
});
//Click listener when clicking on a list item to change the color of the background
$('ul.list').on('click', 'li', function(event) {
$('.selected').removeClass();
$(this).addClass('selected');
});
});
//***************FUNCTIONS**************
function displayQuestion(){
$('.question-number').text('Question Number: '+(current + 1)+"/10" );
if(current < myQuestions.length){
var listQuestion = myQuestions[current];
$('h2').text(listQuestion.question);
$('ul.list').html('');
for (var i = 0; i < listQuestion.answers.length; i++) {
$('ul.list').append('<li id = "'+i+'">'+listQuestion.answers[i] +'</li>');
}
} else {
// show summary that says how many you got correct
displayScore();
}
}
// Checks answer from the array to see if the one chosen is the one that is correct
function checkAnswer(answer){
var listQuestion = myQuestions[current];
if(listQuestion.correct == answer){
score++;
$('li.selected').addClass('correct');
} else {
$('li.selected').addClass('incorrect') ;
$('listQuestion.correct').addClass('correct');
}
$('.score').text('Current Score: '+score);
current++;
}
//Display score
function displayScore(){
$('.questions').hide();
$('.end-quiz').show();
$('.end-score').text("Your score is: " +score + '/10');
if(score >= 8){
$('.comment').text('GREAT JOB!');
}else{
$('.comment').text('You need to work hard');
}
}
body {
box-sizing: border-box;
background: #ff4040;
background-repeat: no-repeat;
background-size: cover;
font-family: 'Nunito', sans-serif;
color:#f2b632;
font-size: 20px;
margin: 0;
}
}
h1 {
margin: 60px 60px 0 60px;
font-size: 30px;
padding-bottom: 30px;
border-bottom: 1px solid #b5b5b7;
color: #ffcc00;
}
h1, h2 {
text-align: center;
font-weight: bold;
letter-spacing: 10px;
text-transform: uppercase;
}
h2 {
font-size: 20px;
}
button {
margin-top: 20px;
width: 300px;
height: 40px;
background: #ffcc00;
font-family: 'Dosis', sans-serif;
font-size: 20px;
color: #ff4040;
border: .5px solid #f2b632;
}
.start-quiz {
width: 500px;
height: 300px;
margin: 100px auto;
text-align: center;
padding-bottom: 200px;
color: white;
}
.questions, .end-quiz {
display: none;
text-align: center;
padding-bottom: 200px;
margin: 100px auto 0 auto;
text-align: center;
width: 500px;
height: 300px;
}
.end-quiz {
border: 2px solid #f2b632;
padding-top: 80px;
height: 100px;
font-size: 30px;
color: #b5b5b7;
}
.question-number, .score {
font-size: 30px;
color: #b5b5b7;
}
ul {
list-style: none;
padding: 0;
}
li {
border: 1px solid #d6d6cf;
width: 200px;
margin: 10px auto;
font-size: 18px;
border-radius: 5px;
padding: 5px;
}
.start-button{
color:white;
}
.selected {
background: #f2b632;
color:#252839;
}
.correct {
background-color: green;
}
.incorrect {
background-color: red;
}
.dot {
height: 110px;
width: 110px;
border-radius: 50%;
display: inline-block;
}
<!DOCTYPE html>
<html>
<head>
<title>Financial Quiz</title>
<link href="https://fonts.googleapis.com/css?family=Bree+Serif|Concert+One|Nunito" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="final.css">
</head>
<body>
<!-- */*************************START PAGE**************************/* -->
<div class="container">
<h1>Financial Quiz</h1>
<div class = "start-quiz">
<p class = 'descrip'>Test your knowledge on the Finance</p>
<button class='start-button dot' >START</button>
</div>
<!-- */******************QUESTIONS********/* -->
<div class = 'questions'>
<h2 class='question'></h2>
<p class= "score"> Score: </p>
<ul class ="list">
</ul>
<div class='submit'>
<button class="submit-button">Check Answer</button>
</div>
<div class='next'>
<button class="next-button">Next</button>
</div>
<p class = 'question-number'></p>
</div>
<!-- */********************COMPLETED PAGE************ -->
<div class = 'end-quiz'>
<p class = 'end-score'></p>
<p class='comment'></p>
<button class="retake-button">RETAKE QUIZ</button>
</div>
</div>
<!-- */****************************************** -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="final.js"></script>
</body>
</html>
Not able to get the green background along with red when the answer is incorrect, and if anyone can tell how to make a pop up box next to correct answer for the explaination.
To fix this you simply need to add the correct class to the li with the index of the answer in your array of objects. To do that change this line in checkAnswer():
$('listQuestion.correct').addClass('correct');
To this:
$('li').eq(listQuestion.correct).addClass('correct');
const myQuestions = [{
'question': 'What is the Full-form of GST?',
'answers': ["Good and Supply Tax", "Goods and Services Tax", "Good and Service Tax", "Great Service Tax"],
'correct': 1
}, {
'question': 'Upper limit on investment in Kisan Vikas Patra (KVP)?',
'answers': ["5000", "10000", "50000", "25000"],
'correct': 0
}, {
'question': "Which insurance company has come up with India's first ever insurance cover for individual victims of cyber crime?",
'answers': ["ICICI", "Muthoot Finance", "LIC", "Bajaj Allianz"],
'correct': 2
}, {
'question': "How much amount will be provided by NITI Aayog to every district to encourage digital payment system?",
'answers': ["Rs 1 lakh", "Rs 2 lakh", "Rs 5 lakh", "Rs 10 lakh"],
'correct': 2
}, {
'question': "What company was the first company to produce a handheld mobile phone?",
'answers': ["Motorola", "Nokia", "Samsung", "Apple"],
'correct': 0
},
{
'question': "What was the first version of Windows?",
'answers': ["Windows 95", "Windows 7", "Windows 1.01", "Windows NT 3"],
'correct': 2
},
{
'question': "Who is the founder of Amazon?",
'answers': ["John Mackey", "Jeff Bezos", "Lee Byung-chul", "Howard Shultz"],
'correct': 1
}, {
'question': "When was Amazon founded?",
'answers': ["2005", "2002", "1996", "1994"],
'correct': 3
}, {
'question': "What does the internet prefix WWW stand for?",
'answers': ["Western Web World", "World Wide Web", "World Wide World", "We Wide Web"],
'correct': 1
}, {
'question': "What is the most used web browser in 2017?",
'answers': ["Safari", "Internet Explorer", "Chrome", "Firefox"],
'correct': 2
}
];
var score = 0;
var current = 0;
$(document).ready(function() {
$(".start-button").click(function() {
$('.start-quiz').hide();
$('.next').hide();
$('.questions').show();
displayQuestion();
$('.score').text('Current Score: ' + score);
});
$(".next-button").click(function(event) {
displayQuestion();
$('.next').hide();
$('.submit').show();
});
$(".submit-button").click(function(event) {
if ($('li.selected').length) {
var answer = $('li.selected').attr('id');
checkAnswer(answer);
$('.next').show();
$('.submit').hide();
} else {
alert('Please select an answer');
}
});
$(".retake-button").click(function() {
location.reload();
console.log("Retake button clicked");
});
$('ul.list').on('click', 'li', function(event) {
$('.selected').removeClass();
$(this).addClass('selected');
});
});
function displayQuestion() {
$('.question-number').text('Question Number: ' + (current + 1) + "/10");
if (current < myQuestions.length) {
var listQuestion = myQuestions[current];
$('h2').text(listQuestion.question);
$('ul.list').html('');
for (var i = 0; i < listQuestion.answers.length; i++) {
$('ul.list').append('<li id = "' + i + '">' + listQuestion.answers[i] + '</li>');
}
} else {
// show summary that says how many you got correct
displayScore();
}
}
function checkAnswer(answer) {
var listQuestion = myQuestions[current];
if (listQuestion.correct == answer) {
score++;
$('li.selected').addClass('correct');
} else {
$('li.selected').addClass('incorrect');
$('li').eq(listQuestion.correct).addClass('correct');
}
$('.score').text('Current Score: ' + score);
current++;
}
function displayScore() {
$('.questions').hide();
$('.end-quiz').show();
$('.end-score').text("Your score is: " + score + '/10');
if (score >= 8) {
$('.comment').text('GREAT JOB!');
} else {
$('.comment').text('You need to work hard');
}
}
body {
box-sizing: border-box;
background: #ff4040;
background-repeat: no-repeat;
background-size: cover;
font-family: 'Nunito', sans-serif;
color: #f2b632;
font-size: 20px;
margin: 0;
}
h1 {
margin: 60px 60px 0 60px;
font-size: 30px;
padding-bottom: 30px;
border-bottom: 1px solid #b5b5b7;
color: #ffcc00;
}
h1,
h2 {
text-align: center;
font-weight: bold;
letter-spacing: 10px;
text-transform: uppercase;
}
h2 {
font-size: 20px;
}
button {
margin-top: 20px;
width: 300px;
height: 40px;
background: #ffcc00;
font-family: 'Dosis', sans-serif;
font-size: 20px;
color: #ff4040;
border: .5px solid #f2b632;
}
.start-quiz {
width: 500px;
height: 300px;
margin: 100px auto;
text-align: center;
padding-bottom: 200px;
color: white;
}
.questions,
.end-quiz {
display: none;
text-align: center;
padding-bottom: 200px;
margin: 100px auto 0 auto;
text-align: center;
width: 500px;
height: 300px;
}
.end-quiz {
border: 2px solid #f2b632;
padding-top: 80px;
height: 100px;
font-size: 30px;
color: #b5b5b7;
}
.question-number,
.score {
font-size: 30px;
color: #b5b5b7;
}
ul {
list-style: none;
padding: 0;
}
li {
border: 1px solid #d6d6cf;
width: 200px;
margin: 10px auto;
font-size: 18px;
border-radius: 5px;
padding: 5px;
}
.start-button {
color: white;
}
.selected {
background: #f2b632;
color: #252839;
}
.correct {
background-color: green;
}
.incorrect {
background-color: red;
}
.dot {
height: 110px;
width: 110px;
border-radius: 50%;
display: inline-block;
}
<link href="https://fonts.googleapis.com/css?family=Bree+Serif|Concert+One|Nunito" rel="stylesheet">
<div class="container">
<h1>Financial Quiz</h1>
<div class="start-quiz">
<p class='descrip'>Test your knowledge on the Finance</p>
<button class='start-button dot'>START</button>
</div>
<!-- */******************QUESTIONS********/* -->
<div class='questions'>
<h2 class='question'></h2>
<p class="score"> Score: </p>
<ul class="list">
</ul>
<div class='submit'>
<button class="submit-button">Check Answer</button>
</div>
<div class='next'>
<button class="next-button">Next</button>
</div>
<p class='question-number'></p>
</div>
<!-- */********************COMPLETED PAGE************ -->
<div class='end-quiz'>
<p class='end-score'></p>
<p class='comment'></p>
<button class="retake-button">RETAKE QUIZ</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Display order of array according to 1-9 and a-z

I have created a dynamic pyramid.
the user can add and remove blocks and the blocks are automatically named
with a number-letter combination, see the picture attached.
I have saved and sorted that combination in a array Array(3) [ "4p", "5i",
"6g" ][]1
Problem:
I would like to display the blocks in the right order, meaning 1-9 and a-z, each time the user clicks "Add Block". As you can seen on the picture, currently 6g comes before 4p.
Is there any way to achieve this?
I have been trying to do this with the following
function newOrder() {
var oldOrder = values;
values.sort();
document.getElementByClassName('.values').innerHTML = values;
}
$(document).ready(function() {
//Add Block Functionality
let values = [];
$('#add-block .button').click(function() {
//determin widht of last div
var lastwidth = $('.pyramid li:last-child .item').width();
//calculation of next div
if (lastwidth == null) {
var plus = 90;
} else {
var plus = lastwidth + 190; //not sure why 190 but with this value they line up smoothly. Was expecting 0 and 100 for the values.
}
//create radom number
var number = Math.floor(Math.random() * 9) + 1;
//create radom letter
function randLetter() {
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var letter = letters[Math.floor(Math.random() * letters.length)];
return letter
}
//make letter available globally
var resultLetter = randLetter();
//create radom color
function randColor() {
var colors = ["green", "yellowgreen", "Chocolate", "goldenrod", "cadetblue", "firebrick", "magenta", "LightSeaGreen", "Peru", "Sienna", "SlateBlue", "Snow", "Tan", "Skyblue"];
var color = colors[Math.floor(Math.random() * colors.length)];
return color
}
//make color available gloabally
var resultColor = randColor();
var $block = $('<li><div class="item" style="width:' + plus + 'px; border-bottom: 60px solid ' + resultColor + ' ;"><input class="values" type="text" placeholder=" ' + number + resultLetter + ' " maxlength="2"> </div></li>');
$('.pyramid').append($block);
//save values
values.push(number + resultLetter);
values.sort();
console.log(values);
});
//Remove Block Functionality
$('#remove-block .button').click(function() {
value = $(".values", $('.pyramid li').last()).attr("placeholder").trim()//find last value added in pyramid//.attr()value of attribute placeholder,trim() is just for white space
values.splice(values.indexOf(value), 1)//indexOf() method returns the position of the first occurrence of a specified value in a string. In this case it is the index of value, which is the last item in the array. Could be replaced by -1 I think
console.log(values)
$('.pyramid li').last().remove();
})
});
body, html {
box-sizing: border-box;
font-size: 16px;
font-family: 'Open Sans', sans-serif;
background-color: #101935;
}
*, *:before, *:after {
box-sizing: inherit;
}
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li div.item {
margin: 0 auto;
position: relative;
height: 0px;
width: 100px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 60px solid #0488e0;
display: flex;
justify-content: center;
}
li div.item:not(.item0){
border-bottom: 60px solid #0488e0;
border-left: 45px solid transparent;
border-right: 45px solid transparent;
margin-top: 10px;
height: 0;
}
.values {
background: rgba(255, 255, 255, .6);
border: none;
text-align: center;
font-size: 15px;
color: black;
font-weight: bold;
height: 20px;
width: 35px;
border-radius: 2px;
position: absolute;
top: 30px;
}
.values:focus {
background: rgba(255, 255, 255, .95);
box-shadow: 0 2px 2px rgba(0, 0, 0, .15);
outline: none;
}
/*buttons section */
.buttons, #add-block, #remove-block{
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
}
#add-block span, #remove-block span {
background-color: #edf7f6;
padding: 5px 15px ;
font-size: 18px;
border-radius: 2px;
color:#888;
font-weight: 400;
}
#add-block .button, #remove-block .button{
background-color: #0488e0;
padding: 5px;
border-radius: 2px;
width: 40px;
text-align: center;
display: block;
font-size: 20px;
color: #ffffff;
margin: 10px;
transition: background-color 250ms ease-in-out 100ms;
}
#add-block .button:hover, #remove-block .button:hover{
background-color: #059BFF;
cursor: pointer;
}
<body>
<ul class="pyramid">
</ul>
<section class="buttons">
<div id="add-block">
<span>Add Block</span>
<div class="button">+
</div>
</div>
<div id="remove-block">
<span>Remove Block</span>
<div class="button">-
</div>
</div>
</section>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="resources/js/main.js"></script>
</body>
The core problem which you need to solve is to have a sorted array where
1-numbers should be in high to low order
2-if two numbers are same, their alphabets should be considered i.e high to low
you can use the Array's builtin sort function and provide custom comparator to achieve this
note:instead of concatenating number and alphabet you can also make an object with two properties that will help you write simplified comparator, while you can always concatenate both properties while rendering in html
var myStrings=[{num:'1',char:'z'},{num:'9',char:'a'},{num:'1',char:'b'},{num:'9',char:'d'}]
function myCustomComparator(a,b){
if (a.num<b.num) {
return -1;
}
else if (a.num>b.num) {
return 1;
}
// a.num must be equal to b.num
if (a.char<b.char) {
return -1;
}
else if (a.char>b.char) {
return 1;
}
//char must be equal too
return 0;
}
myString.sort(myCustomComparator);
^above code is not tested though but you would have an idea by now how to use custom comparator to achieve what you want you can further read about it here

Should I use sessionStorage and if so, how?

I have built a simple task app that allows you to add different tasks. It works fine. I am not sure what is the best approach however to retain the data/HTML once the page is refreshed. I have heard of HTML5 session/localStorage but I am not sure if this would be the best method to use in this situation. Also, I would need help making this work if sessionStorage was a good choice.
window.onload = init;
function init() {
var generateBtn = document.getElementById("generate");
generateBtn.onclick = addTask;
var tasksWrapper = document.getElementById("tasksWrapper");
var taskDesc = document.getElementById("taskDesc");
}
var taskId = 0;
var taskBarArray = [];
function addTask() {
taskId++;
var taskBar = document.createElement("div");
var taskBarInput = document.createElement("input");
var taskBarDeleteBtn = document.createElement("input");
taskBar.setAttribute("id", taskId);
taskBar.setAttribute("class", "taskBar");
taskBarInput.setAttribute("class", "taskDesc");
taskBarInput.setAttribute("type", "text");
taskBarInput.setAttribute("placeholder", "Enter task");
function rmPlaceholder() {
taskBarInput.removeAttribute("placeholder", "Enter task");
}
function addPlaceholder() {
taskBarInput.setAttribute("placeholder", "Enter task");
}
taskBarInput.onfocus = rmPlaceholder;
taskBarInput.onblur = addPlaceholder;
taskBarInput.setAttribute("name", "taskDesc");
taskBarInput.setAttribute("value", taskDesc.value);
taskBarDeleteBtn.setAttribute("class", "deleteBtn");
taskBarDeleteBtn.setAttribute("type", "button");
taskBarDeleteBtn.setAttribute("value", "x");
var addTaskBar = tasksWrapper.appendChild(taskBar);
var targetTaskId = document.getElementById(taskId);
var addTaskBarInput = targetTaskId.appendChild(taskBarInput);
var AddTaskBarDeleteBtn = targetTaskId.appendChild(taskBarDeleteBtn);
taskBarArray.push(taskBar);
taskDesc.value = "";
taskBarDeleteBtn.onclick = removeTask;
function removeTask(e) {
taskBarDeleteBtn = e.target;
tasksWrapper.removeChild(taskBar);
taskBarArray.pop(e);
if (taskBarArray.length < 1) {
taskId = 0;
}
}
}
#main_wrapper {
margin: 0 auto;
max-width: 528px;
width: 100%;
height: 20px;
}
.taskBar {
width: 100%;
background: #333230;
border-bottom: 1px solid #fff;
border-radius: 10px;
}
.taskDesc {
margin: 10px 0 10px 10px;
background: none;
border: none;
outline: none;
font-size: 20px;
color: #fff;
text-transform: uppercase;
z-index: 9999;
}
.deleteBtn {
margin: 6px 6px 0 0;
padding: 6px;
width: 32px;
background: #8F0A09;
font-size: 15px;
color: #fff;
border-radius: 100px;
border-color: #000;
float: right;
outline: none;
}
#header {
padding: 10px;
background: #000;
border-bottom: 1px solid #fff;
border-radius: 10px;
}
#taskDesc {
padding: 2px 0;
width: 50%;
font-size: 20px;
}
#generate {
padding: 5px 83px;
background: #82CC12;
font-size: 20px;
border-color: #000;
border-radius: 5px;
outline: none;
}
::-webkit-input-placeholder {
color: #4C4B48;
}
::-moz-placeholder {
color: #4C4B48;
}
:-ms-placeholder {
color: #4C4B48;
}
<div id="main_wrapper">
<div id="header">
<input type="text" id="taskDesc"></input>
<input type="button" id="generate" value="Add task">
</div>
<div id="tasksWrapper">
</div>
</div>
Here I would use localStorage, it will be remembered even after the session has timed out. A session is probably ended if the user restarts their browser.
The only problems I see with localStorage is the 10 MB size limit on desktops (2 MB om mobile devices I think), and that it's not easy enough to get data from localStorage to the server. But localStorage would be a perfect fit for a TODO app with simple items.

Categories

Resources