0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I agree and I doubt it holds any actual value/weight on it so I think it is safe to remove it
@JeffreyKlinkhamer: I believe you should clarify your question then, e.g. change current_score in the rhs of the assignments to be different in each line.
current_score is a variable defined outside my function it keeps track of the score per question block, Simply put var current_score = 0; function calculate_score(questions, score). it changes per element the problem is that it's always placed on score_label[0]
When I run the code document.getElementById("score_label.length()") it returns null. Does this mean my score_label isn't initialized properly? Also I've changed that line to echo "your total score: <span id='score_label[".$score_board."]'></span>";
It seems you are mixing up PHP and JavaScript, don't you? The first line is in JS, trying to find an element with the id attribute equal to the string score_label.length() (which, of course, does not exist.) The second one is PHP, writing HTML code into the output document.
|
0

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

need to loop through a PHP array in JavaScript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.