Reputation: 725
In my case, I want to display the total of heads+tails, each time I press toss
, so that toss in this case will be also changing dynamicaly.
The problem is that how can I add heads+tails and show their total each time I clicks on toss.
Here is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<script type="text/javascript">
<!--
var heads = 0;
var tails = 0;
function toss() {
var headsField = document.getElementById("heads");
var tailsField = document.getElementById("tails");
if (flip()) {
++heads;
headsField.value = heads;
} else {
++tails;
tailsField.value = tails;
}
}
// end function toss
function flip() {
return Math.floor(Math.random() * 9) == 1
}
// end function flip
</script>
<title></title>
</head>
<body>
<form action="">
<table border="1">
<tr>
<td>Heads</td>
<td><input id="heads" type="text"></td>
</tr>
<tr>
<td>Tails</td>
<td><input id="tails" type="text"></td>
</tr>
<tr>
<td><input onclick="toss()" type="button" value="Toss"></td>
</tr>
</table>
</form>
</body>
</html>
Upvotes: 0
Views: 336
Reputation: 7301
Add heads + tails
. See Fiddle.
New Table Row
<tr>
<td>Total</td>
<td>
<input id="total" type="text">
</td>
</tr>
JavaScript
var heads = 0;
var tails = 0;
function toss() {
var headsField = document.getElementById("heads");
var tailsField = document.getElementById("tails");
var total = document.getElementById("total");
if (flip()) {
headsField.value = ++heads;
} else {
tailsField.value = ++tails;
}
total.value = (heads + tails);
} // end function toss
function flip() {
var msg = Math.floor(Math.random() * 9) == 1;
return msg;
} // end function flip
OUTPUT
Upvotes: 1