Barri
Barri

Reputation: 44

I can't get image to display using Javascript

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

Answers (3)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11045

There are multiple faults with your codes.

  1. You have two questions but you are selecting the true if there is only 1 correct answer.
  2. you have assigned src to div but it should be assigned to img.
  3. the result of (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.
  4. You have multiple id of goodorbad and using ID selector, only selects the first occurance.

Upvotes: 1

Hemant Parashar
Hemant Parashar

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

kht
kht

Reputation: 590

You cannot have multiple HTML elements with the same ID, they must be unique.

You should use classes and/or data-attributes if you want to select multiple elements at the same time.

Upvotes: 0

Related Questions