Reputation: 44
Am working on a quiz where i need an image to show good or bad when i click submit, if the correct or wrong answers are chosen. But i keep getting only one image displayed.
HTML
<div class = "question1">
<p>What is the capital of Nigeria?</p>
<input type = "text" id = "question_one">
<div id = "goodorbad"></div>
</div>
<div class = "question2">
<p>Which of these is the symbol for 'plus'?</p>
<select id = "operators">
<option value = "x">x</option>
<option value = "-">-</option>
<option value = "+">+</option>
<option value = "%">%</option>
</select>
<div id = "goodorbad"></div>
</div>
JAVASCRIPT
function getResult() {
let answer_one = document.getElementById("question_one").value;
let answer_two = document.getElementById("operators").value;
let correct_ans = 0;
if (answer_one === "abuja") {
correct_ans++;
}
if (answer_two === "+") {
correct_ans++;
}
let sign_symbol = ["bad1.png" , "good1.png"];
let sign;
if (correct_ans === true){
sign = 1;
}
else{
sign = 0;
}
document.getElementById("goodorbad").src = sign_symbol[sign];
If an answer is correct, then the good1.png image should display at the right hand corner and if an answer is incorrect, the bad1.png image should display
Upvotes: 1
Views: 696
Reputation: 11045
There are multiple faults with your codes.
src
to div
but it should be assigned to img
.correct_ans === true
) is always false. Because three equal sign compares both values and types and a number type is never equal to boolan type.goodorbad
and using ID selector, only selects the first occurance.Upvotes: 1
Reputation: 3774
You're using a src
attribute on a div
instead of an img
tag which won't work. Also, use a generic class e.g question-img
for common elements, in this case the img tag rather than using the same id for multiple elements which is a bad practice.
<div class = "question1">
<p>What is the capital of Nigeria?</p>
<input type = "text" id = "question_one">
<img class="question-img" src=""/>
</div>
and use document.querySelector
like to assign the src
to the img
element
document.querySelector("#question1 .question-img").src = sign_symbol[sign];
Also your if (correct_ans === true)
statement is always going to be false since you're comparing a number with a boolean.
Hope this helps !
Upvotes: 2