I'm working on a trivia app that generates questions from an API. I want the questions generated to be for the category/ difficulty selected once the get question button is clicked. Right now it's generating random questions on the console when the page loads. I'm unclear where I'm going wrong?
So far my code is like:
const score = document.querySelector('#score');
const output = document.querySelector('#output');
const answerSelect = document.querySelector('#selAnswers');
const btn = document.querySelector('#btn');
const categories = [
'Sports',
'Art',
'Vehicles',
'History'
];
const difficulty = [
'easy',
'medium',
'hard'
];
btn.addEventListener('submit', function(e) {
e.preventDefault();
});
document.addEventListener('DOMContentLoaded', function() {
let categorySelect = document.querySelector('#category');
let difficultySelect = document.querySelector('#difficulty');
let html = '';
for (let item of categories) {
// Appending Strings created using Template literals
html += `<option>${item}</option>`;
}
categorySelect.innerHTML = html;
for (let item of difficulty) {
let opt = document.createElement('option');
// <option> will use its .textContent as value if not explicitly defined
opt.textContent = item;
difficultySelect.append(opt);
}
});
$.ajax ({
url: 'https://opentdb.com/api.php?amount=10',
data: '{}',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.results[0]);
data.items.forEach(function(item){
//console.log(item);
let output = getOutput(item);
//Display Results
result.innerHTML += output;
});
},
error: function(jqXHR, textStatus, ex ){
console.log(`${textStatus}, ${ex}, ${jqXHR.responseText}`);
alert(`${textStatus}, ${ex} ${jqXHR.responseText}`);
}
});
//function
function getQuestion(){
result.innerHTML ='';
btn.innerHTML ='';
let categoryOption = categories.value;
let difficultyLevel = difficulty.value;
}
HTML:
<!doctype html>
<html lang="en">
<head>
<title>Trivia</title>
<link rel='stylesheet' href='css/Trivia.css' >
</head>
<body>
<h1>Trivia</h1>
<div>Score: <span id='score'>Correct 0 Wrong 0</span></div>
<br>
<div>
<label>Select Category:</label>
<select id='category'></select>
<br>
<label>Select Difficulty:</label>
<select id='difficulty'></select>
</div>
<br><br>
<div id='output'></div>
<br>
<div id='selAnswers'></div>
<br>
<button id='btn' type='submit'>Get First Question!</button>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src ='js/Trivia.js'></script>
</body>
</html>