John Vasiliou
John Vasiliou

Reputation: 997

Score not incrementing javascript

My score increment is not working. Two questions.

Will it automatically update?

Or is my code wrong?

HTML Page

<script>document.write("Score: " + score);</script>

<table class="widthOneHundredPercent">
<tr>
 <td class="tableCellFloat columnOne" valign="top">
  <div class="question"><b>Question 1:</b> Who is the youngest in B Media?</div>
 <td class="tableCellFloat columnTwo" valign="top">   
     <div class="answers">
            <ol>
                <li>
                    <input type="radio" name="q1" id="q1-a" onclick="unhide(this); scoreIncrement()"/>John
                </li>
                <li>
                    <input type="radio" name="q1" id="q1-b" onclick="unhide(this)"/>Paula
                </li>
                <li>
                    <input type="radio" name="q1" id="q1-c" onclick="unhide(this)"/>Henal
                </li>
                <li>
                    <input type="radio" name="q1" id="q1-d" onclick="unhide(this)"/>Malc
                </li>
            </ol>
        </div>
 </td>
 </td>
</tr>
<tr>
 <td colspan="2" valign="top">
    <div id="answerq1a" class="hidden">
 <p>Your answer is correct, John is 20.</p>
    </div>
 </td>
</tr>
<tr>
 <td colspan="2" valign="top">
    <div id="answerq1b" class="hidden">
 <p>Your answer is incorrect, Paula is 31.</p>
    </div>
 </td>
</tr>
<tr>
 <td colspan="2" valign="top">
    <div id="answerq1c" class="hidden">
 <p>Your answer is incorrect, Henal is 21.</p>
    </div>
 </td>
</tr>
<tr>
 <td colspan="2" valign="top">
    <div id="answerq1d" class="hidden">
 <p>Your answer is incorrect, Malc is 33.</p>
    </div>
 </td>
</tr>
</table>​

Javascript

var currentShown = "";

function unhide(rad) {
    var id = "answer" + rad.id.replace("-", "");
    var answer = document.getElementById(id);
    if (answer) {
        var current = document.getElementById(currentShown);
        if (current) current.className = "hidden";
        currentShown = id;
        answer.className = "unhidden";
    }
}

var score = 0;

function scoreIncrement() {

    score++;
}​

Such simple code, yet it wont work, obviously I've written it wrong but I cannot see what is wrong?

Upvotes: 1

Views: 1163

Answers (1)

Mike McMahon
Mike McMahon

Reputation: 8604

You're document.write'ing the score out, but never updating the call so even though your score increments it's not being updated on the page...

Update your HTML with something like:

<!-- <script>document.write("Score: " + score);</script> -->
<span id="score"></span>

and your javascript with something like

function scoreIncrement() {
    score++;
    document.getElementById("score").innerText="Score: " + score; 
}​

That should do it. The most elegant solution, maybe not, but it does work.

Upvotes: 4

Related Questions