Reputation: 141
I am trying to get the value of each of the three scores and add them up and display them in "Total:". My problem is that I cannot figure out how to make it so that every time one of the score values change, the corresponding total changes with it.
Would I be able to somehow invoke "onchange" somewhere to make this work? Thanks.
<!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>
Here is my JavaScript class getTotal.js
function total() {
var score1 = document.getElementById("score1");
var score2 = document.getElementById("score2");
var score3 = document.getElementById("score3");
return score1 + score2 + score3;
}
function assign() {
var totalScore = document.getElementById("total");
totalScore = total;
}
Upvotes: 1
Views: 88
Reputation: 53246
Your code 'as is' won't work. As I mentioned in my comment, you need to look at parseFloat()
(or parseInt()
depending upon the values you allow), and also the value
property of DOM objects. Finally, onchange
or onkeyup
events can be used for user interaction.
Combining all of these will give you the following, working sample:
var score1Field = document.getElementById('score1'),
score2Field = document.getElementById('score2'),
score3Field = document.getElementById('score3');
function sumit()
{
var score1 = parseFloat( score1Field.value ),
score2 = parseFloat( score2Field.value ),
score3 = parseFloat( score3Field.value );
if( isNaN( score1 ) ) { score1 = 0; }
if( isNaN( score2 ) ) { score2 = 0; }
if( isNaN( score3 ) ) { score3 = 0; }
total = score1 + score2 + score3;
document.getElementById('total').innerHTML = total;
}
// Bind our events:
score1Field.onkeyup = sumit;
score2Field.onkeyup = sumit;
score3Field.onkeyup = sumit;
// Call it when the page loads to handle default values:
sumit();
Upvotes: 1
Reputation: 277
Yes you can use onchange and wrap your total() and assign() functions inside it. See this link for onchange usage: http://www.w3schools.com/jsref/event_onchange.asp
Upvotes: 0
Reputation: 965
Yes, use an onchange event to recalculate when the value changes (after you focus away from the input), or use keydown if you want it to recalculate as you type.
Upvotes: 0