Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to add up 3 input elements of type number. This doesn't work for some reason. When I take out the if statements, it works, but only after I change the first one (score1). When I change the others, nothing happens. Thanks.

function getTotal() {

var score1 = document.getElementById("score1");
var score2 = document.getElementById("score2");
var score3 = document.getElementById("score3");

var sc1 = parseInt(score1.value);
var sc2 = parseInt(score2.value);
var sc3 = parseInt(score3.value);

if (isNan(sc1)) {
    sc1 = 0;
}

if (isNan(sc2)) {
    sc2 = 0;
}

if (isNan(sc3)) {
    sc3 = 0;
}

var total = sc1 + sc2 + sc3;
document.getElementById("totalScore").innerHTML = total;

}

function assign() {
    var score1 = document.getElementbyId("score1");
    var score2 = document.getElementbyId("score2");
    var score3 = document.getElementbyId("score3");    

    score1.onchange = getTotal;
    score2.onchange = getTotal;
    score3.onchange = getTotal;
}


<!DOCTYPE html>
<html>
  <head>
    <script src="getTotal.js"  type="text/javascript"></script>
  </head>
  <body>
    <header>
      <tbody>
        <tr>
          <td>
            Total: 
            <output id="total" class="totalScore"></output>
          </td>
        </tr>
      </tbody>
    </header>
  <table>
    <tbody>
      <td>Score 1</td>
      <td><input type="number" id="score1"/></td>

      <td>Score 2</td>
      <td><input type="number" id="score2" /></td>

      <td>Score 3</td>
      <td><input type="number" id="score3" /></td>
    </tbody>
  </table>

   <script type="text/javascript">assign();</script>

  </body>
 </html>
share|improve this question

2 Answers 2

Spelling mistake.

var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");  

If you check your console you will see the error Uncaught TypeError: undefined is not a function on the line where you are calling score1. The selector is document.getElement*By*Id, you were writing by lowercase..

share|improve this answer

Your <output> has an id attribute with the value is "total" whereas your class attribute' value is "totalscore". Consider changing the id value to "totalscore" or change getElementById's value to"score"

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.