• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Java script quiz

Object Storage Arubacloud
0 głosów
243 wizyt
pytanie zadane 31 maja 2022 w JavaScript przez olek1405 Nowicjusz (180 p.)

 Witam, staram się zrobić quiz za pomocą javascript, potrzebował bym pomocy z walidacja odpowiedzi, gdy użytkownik wpisuje poprawna odpowiedź powinien pokazać  alert że wpisał poprawną odpowiedź i kod powinien przejść  do kolejnej odpowiedz, niestety kod który napisał tego nie robi

Byłbym wdzięczny za sugestie jak do tego się zabrać oraz za wszelkie wskazówki dotyczące kodu i jak go ulepszyć 

Dziękuje i pozdrawiam, poniżej załączam kod html css i javascript oraz link do codepen

https://codepen.io/aleksandergale2/pen/BaYrbqg

let userinputName = prompt('Please enter your name');
let result = userinputName.toUpperCase();
document.getElementById("name").innerHTML = result;
const startButton = document.getElementById('btn')
const nextButton = document.getElementById('nextBtn')
let shuffleQuestions, currentQuestionIndex
const QuestionContainerElement = document.getElementById('question-container')
const paragraph= document.getElementById('welcome')
const questionElement = document.getElementById('question')




startButton.addEventListener('click', startGame)
    
function startGame(){
    console.log("started")
    startButton.classList.add('hide')
    nextButton.classList.remove('hide')
    shuffleQuestions = questions.sort(() => Math.random() - .5) 
    currentQuestionIndex = 0
    showQuestion(shuffleQuestions[currentQuestionIndex])

    QuestionContainerElement.classList.remove('hide')
    paragraph.classList.add('hide')

}
nextButton.addEventListener('click', () => {
    currentQuestionIndex++
    setNextQuestion()
})

function setNextQuestion(){
    showQuestion(shuffleQuestions[currentQuestionIndex])
    if (shuffleQuestions.length > currentQuestionIndex + 1) {
        nextButton.classList.remove('hide')
      } else {
        startButton.innerText = 'Restart'
        startButton.classList.remove('hide')
        nextButton.classList.add('hide')

      }

    



}
function showQuestion(question){
    let input=document.getElementById('textbox').value;
    questionElement.innerText = question.question
    if(input == questions.answer) {
        alert("Correct answer");

    }
}
const questions = [
    {
      question: 'What is the capital of france?',
       answer : "paris"
        
        
      
    },
    {
      question: 'What is the capital of wales?',
      answer: "Cardif"
        
      
    },
    {
      question: 'what is the capital of Italy?',
      answer: "Rome"
    
      
    },
    {
      question: 'What is the capital of Scotland',
      answer: "Edinburgh"
        
      
    }
  ]
#container {
  width: 500px;
  margin: 10rem auto;
  padding: 1rem;
  font-family: "Gill Sans MT";
  font-size: 2rem;
  text-align: center;
  color: #fff;
  background-color: rgb(42, 161, 240);
}

button {
  border: none;
  border-radius: 10px;
  padding: 1rem;
  color: #fff;
  font-weight: 900;
  cursor: pointer;
  background-color: rgb(178, 81, 202);
}
.hide{
  display: none;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HNC QUIZ ASSESSMENT TEMPLATE</title>
    <link rel="stylesheet" href="css/quiz_assess_styles.css"> </head>

<body>
    <div id="container">
        <p id="welcome">WELCOME TO THE QUIZ <span id="name"> ...name here... </span></p>
        <div id="question-container" class="hide">
        <div id="question">Question</div>

            <input id="textbox" type="text" name="answer">
        
        </div>
        <button id="btn">START QUIZ</button>
        <button id="nextBtn" class="hide">Next Question</button>

    </div>
    

    
    <script src="js/quiz_assess_script.js"></script>
</body>

</html>
    

 

1
komentarz 31 maja 2022 przez VBService Ekspert (253,300 p.)
edycja 31 maja 2022 przez VBService

Na chromie jak dam Anuluj

let userinputName = prompt('Please enter your name');

quiz nie działa. Przycisk "START QUIZ" nie reaguje na zdarzenie click.

Zamiast prompt proponuje użyć np. modal box.

 

 

 

P.S. Na forum jakiś czas temu było takie pytanie, może będzie inspiracją.  wink

1 odpowiedź

+1 głos
odpowiedź 1 czerwca 2022 przez VBService Ekspert (253,300 p.)
edycja 1 czerwca 2022 przez VBService

W funkcji showQuestion masz sprawdzanie poprawności odpowiedzi, proponuje wydzielić ten kawałek kodu do osobnej funkcji np. checkAnswer i  z niej dopiero wywołać kolejne pytanie gdy zajdzie warunek

    if (input == questions.answer) {
        alert("Correct answer") 
    }

 

propozycja zmian

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>HNC QUIZ ASSESSMENT TEMPLATE</title>
    <link rel="stylesheet" href="css/quiz_assess_styles.css">
  </head>

  <body>
    <div id="container">
      <p id="welcome">WELCOME TO THE QUIZ <span id="name">...</span></p>
      <div id="question-container" class="hide">
        <div id="question">Question</div>
        <input id="answer" type="text" name="answer">
      </div>
      <button id="startBtn">START QUIZ</button>
      <button id="checkanswerBtn" class="hide">Check Answer</button>
    </div>

    <script src="js/quiz_assess_script.js"></script>
  </body>
</html>
#container {
  width: 500px;
  margin: 10rem auto;
  padding: 1rem;
  font-family: "Gill Sans MT";
  font-size: 2rem;
  text-align: center;
  color: #fff;
  background-color: rgb(42, 161, 240);
}
p#welcome span {
  display: block;
  font-size: 2rem/1.1;
}
button {
  border: none;
  border-radius: 10px;
  margin: 1rem 0; /* dodane */
  padding: 1rem;
  color: #fff;
  font-weight: 900;
  cursor: pointer;
  background-color: rgb(178, 81, 202);
}
.hide{
  display: none;
}
let startButton, checkanswerButton 
let questionElement, QuestionContainerElement, paragraph
let shuffleQuestions, currentQuestionIndex
 
window.onload = load
 
function load() {
  startButton = document.getElementById('startBtn')
  startButton.addEventListener('click', startGame)
 
  checkanswerButton = document.getElementById('checkanswerBtn')
  checkanswerButton.addEventListener('click', checkAnswer)
 
 
  QuestionContainerElement = document.getElementById('question-container')
  paragraph = document.getElementById('welcome')
  questionElement = document.getElementById('question')
 
  const userinputName = prompt('Please enter your name') || '...'
  document.getElementById('name').textContent = userinputName.toUpperCase()
}
 
function startGame() {
  console.log('started')
  startButton.classList.add('hide')
  checkanswerButton.classList.remove('hide')
  shuffleQuestions = questions.sort(() => Math.random() - .5)
  QuestionContainerElement.classList.remove('hide')
  paragraph.classList.add('hide')
 
  currentQuestionIndex = 0
  showQuestion()
}
 
function setNextQuestion() {    
  if (shuffleQuestions.length > currentQuestionIndex + 1) {
    currentQuestionIndex++
    showQuestion()
    checkanswerButton.classList.remove('hide')
    QuestionContainerElement.classList.remove('hide')
  } else {
    startButton.textContent = 'Restart'
    startButton.classList.remove('hide')
    checkanswerButton.classList.add('hide')
    QuestionContainerElement.classList.add('hide')
  }
}
 
function showQuestion() {
  const question = shuffleQuestions[currentQuestionIndex]
  questionElement.textContent = question.question
  const input = document.getElementById('answer')
  input.value = null
  input.focus()
}
 
function checkAnswer() {
  const question = shuffleQuestions[currentQuestionIndex]
  const input = document.getElementById('answer') 
  if (input.value.toLowerCase() == question.answer.toLowerCase()) {
    alert("Correct answer")
    setNextQuestion()
  } else {
    alert("Incorrect answer")
  }
  input.focus()
}
 
const questions = [
  {
    question: 'What is the capital of France?',
      answer: 'Paris'
  },
  {
    question: 'What is the capital of Wales?',
      answer: 'Cardif'
  },
  {
    question: 'what is the capital of Italy?',
      answer: 'Rome'
  },
  {
    question: 'What is the capital of Scotland',
      answer: 'Edinburgh'
  }
]

 

1
komentarz 1 czerwca 2022 przez olek1405 Nowicjusz (180 p.)
Dziękuję właśnie o to mi chodziło

Podobne pytania

+1 głos
0 odpowiedzi 108 wizyt
pytanie zadane 27 grudnia 2021 w JavaScript przez ferdynand Obywatel (1,250 p.)
0 głosów
2 odpowiedzi 1,221 wizyt
pytanie zadane 30 kwietnia 2021 w JavaScript przez Ktosi Nowicjusz (140 p.)
+1 głos
2 odpowiedzi 404 wizyt
pytanie zadane 3 marca 2021 w JavaScript przez Comparion Obywatel (1,810 p.)

92,568 zapytań

141,422 odpowiedzi

319,629 komentarzy

61,956 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...