I'm developing a quiz app and there is two main function:
- fetchData
This function will fetch questions from a API and display everything to the webpage.
- isCorrect
This function will check if the answer is correct typed by the user. If it is, add 1 to the score variable. But when the first function runs, it doesn't show me anything. My guess is that the option is not properly displayed or something. Here is my first function's code:
async function fetchData() {
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i ) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
console.log(choices);
});
document.getElementById('choice').add(html_container.join());
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
document.getElementById('answer_element').style.display = "none";
document.getElementById('answer_element').innerHTML = "The answer to this question is " toJS.results[0].correct_answer;
}
fetchData();
I got this error on the console:
Uncaught (in promise) TypeError: Failed to execute 'add' on 'HTMLSelectElement': The provided value is not of type '(HTMLOptGroupElement or HTMLOptionElement)'.
But I clearly added my options to a select element with an id of choice.
CodePudding user response:
Post
I'm assuming line 23
is the error since it was the only add
method shown. The error is caused by passing a string (html_container.join()
) to the add
method, but it is expecting (as stated and as referenced here) an HTMLOptGroupElement
or HTMLOptionElement
. To fix this issue, you have at least two options:
createElement
Use document.createElement('option')
when creating the option element as follows:
var option = document.createElement('option');
option.value = choices;
option.innerHTML = choices;
document.getElementById('choice').add(option);
innerHTML
Use .innerHTML
to add the string to the select element's inner HTML as follows:
document.getElementById('choice').innerHTML = html_container.join(); // use = to append