Jeffrey Klinkhamer
Jeffrey Klinkhamer

Reputation: 415

JavaScript using an array to display data

I'm working on a score system that shows per question block, I'm using PHP to retrieve the data from a table and the javascript below to calculate the score. The problem is I want several score labels underneath each question block. So clearly I need an array to make this work, but currently I'm using this line to write the data onto document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); so this only applies to the first entry in the array. How do I make it loop through the entire array(score_label[]) and increase it's value so the code reads document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1);

this is the element javascript is writing to
echo "your total score: <span id='score_label[0]' name='score_board['".$score_board."']'></span>";
if there is need for I can post the entire function but I think it's mostly my lack of knowledge on arrays that's the issue here

Upvotes: 0

Views: 192

Answers (2)

Alexander Pavlov
Alexander Pavlov

Reputation: 32306

If I'm reading your question correctly (current_score is the same for all elements???):

for (var i = 0; i < score_label.length; ++i)
    document.getElementById("score_label[" + i + "]").innerHTML=""+current_score.toFixed(1);

I should mention that the id attribute of the form score_label[N] may be confusing.

Upvotes: 1

SoEnLion
SoEnLion

Reputation: 183

Try to use foreach function to loop through the whole score_label array.

need to loop through a PHP array in JavaScript

Upvotes: 0

Related Questions