Bradly Spicer
Bradly Spicer

Reputation: 2318

populate one div with array data on if statement

I have 5 div tags all with the same id "answer" these div tags need to execute this script: document.getElementById("answer").innerHTML = answer;

when a trigger is made (Already completed, but for reference):

var arrAnswers = ["specialword", "word1", "word2" "word3" "word4"];
socket.on('answer', function (answer) {
    console.log('answer: ' + answer);
        if ( $.inArray(answer, arrAnswers) > -1 ) {
            console.log('correct answer!');
        } else {
            console.log('incorrect answer :(');
        }
});

I have this in my HTML:

<div class="answer"></div>
<div class="answer"></div>
<div class="answer"></div>
<div class="answer"></div>
<div class="answer"></div>

I need to make it so that if the answer is correct, it picks ONE empty div tag and populates it with the answer specified from the variable "answer".

I could in theory do an if statement for if the innerhtml is empty, but that would return the other results too. I could also do an if else statement so it queries if it's empty, if so do the .innerhtml section and then break out. But that seems too long.

What's the shortest logicalway of going about this?

Thanks in advance

Upvotes: 0

Views: 196

Answers (1)

fsacer
fsacer

Reputation: 1402

Here you can use document.getElementsByClassName("answer") array, use Math.random() * lengthOfArray to generate random number and then using indexer access element and set the innerHTML for that element. So this would look like this:

var arrAnswers = ["specialword", "word1", "word2" "word3" "word4"];
var answers = document.getElementsByClassName("answer");
var index = Math.random() * answers.length;
socket.on('answer', function (answer) {
    console.log('answer: ' + answer);
        if ( $.inArray(answer, arrAnswers) > -1 ) {
            console.log('correct answer!');
            answers[index].innerHTML = answer; //set answer
        } else {
            console.log('incorrect answer :(');
        }
});

Upvotes: 1

Related Questions