Running total of single die - Javascript - javascript

I am trying to create an application that has a die, singular for dice, on the screen. When you click the die, it will roll and display a number. I also want to keep a running total of each roll.
So far I have it to where each time the button is clicked, the image randomly changes. I'm confused about how to keep a running total of the rolls, however.
Here is the code I have so far.
<html>
<head>
</head>
<body>
<script>
function displaydie() {
var total = 0;
var num = ("src",(Math.floor(Math.random()*6)+1) + ".jpg")
document.getElementById("die").setAttribute("src", (Math.floor(Math.random()*6)+1) + ".jpg")
}
</script>
<img id="die" alt="die"/>
<br/>
<input type="button" value="Click me!" onclick="displaydie()"/>
<span id="total"/></span>
</body>
</html>

Use a global variable to store the total value then add the value of the current dice to the total. For that you need to store the value of the current dice in a variable and use it for the image and to add.
var total = 0;
function displaydie() {
var num = (Math.floor(Math.random() * 6) + 1);
total += num;
document.getElementById("die").setAttribute("src", num + ".jpg")
document.getElementById("total").innerHTML = total;
}
Demo: Fiddle

You want to create a dictionary, and on each roll, add to the number of times you have rolled that number:
var rolls = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
var total=0;
function displaydie()
{
var num= Math.floor(Math.random()*6)+1
rolls[num]+=1
total+=1
document.getElementById("die").setAttribute("src",num + ".jpg")
document.getElementById("total").innerHTML = "Total rolls: "+total+"\n"+"1: "+rolls[1]+" 2: "+rolls[2]+" 3: "+rolls[3]+" 4: "+rolls[4]+" 5: "+rolls[5]+" 6: "+rolls[5]
}
DEMO

Related

How to use JavaScript Math.random() within HTML p tag

I am trying to print 1 random number within my <p> in HTML.
JavaScript:
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
HTML:
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - [randomNumber] <br/> stat 2 - [randomNumber] </p>
</div>
</div>
(I could not get my HTML to post normally so I had to make it ugly. Sorry...)
My random number will print off to the side, and it is unable to print more within the same p. I was wondering if there is a way to place my random number from JavaScript within my p in HTML and keep all the css settings within the other div class card.
Thank you!
If I understand your question correctly, you want to place the random number in the p instead of the div, and have it append each time.
You should create an element each time with document.createElement and append it to the div, like this
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
var newNumber = document.createElement("p");
newNumber.innerText = randomNumber;
document.getElementById("randomNum").appendChild(newNumber);
return false; // Returns false just to tidy everything up
}
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
//document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
var x = document.getElementsByClassName("randNum");
x[0].innerHTML = randomNumber;
x[1].innerHTML = randomNumber;
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - <span class="randNum"></span> <br/> stat 2 - <span class="randNum"></span> </p>
</div>
</div>
</body>
</html>
You have to give the P element a ID, then do a document.getElementbyID(whatever you put the ID for in the P tag) = randomNumber Your Html should be
<p id="whatever you want"></p>
Hopefully that helps.

Adding sum of an array but getting NAN

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>
The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).
With minimal changes, this should work:
function sumit() {
let text = parseInt(document.getElementById("inp").value) || 0;
let hours = document.getElementById("hours");
let total = 0;
total += text;
hours.innerHTML = `You have studied a total of ${total} hours.`;
}
Explanation
parseInt can return NaN, so we use the || operator to let it default to 0
You don't need to loop over anything to sum the number
Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
You don't need to add total to text multiple times

Need help making a tip calculator

I need to make a program that will take a number and multiply it by .15 so you know how much of a tip you need to leave.
I tried to put my bill input into a new variable in my function because I would get the tip total when I took the number () out of my new variable, but doing this lead to nothing happening as JavaScript doesn't know it's a number
<body>
<input id="bill" placeholder ="How much was you meal?" />
<button onclick ="tip()"> submit</button>
<script> let bill = document.querySelector("#bill")
function tip(){
let yourTip = number( bill.value * .15)
let total = yourTip * bill
console.log ("Your tip is $" + yourTip)
console.log ("Your total after the tip is $" + total)
}
</script>
</body>
I don't need to print it on the screen just in the console and the tip % does not need to change.
try this
<input id="bill" type="number" placeholder="How much was you meal?" />
<button onclick="tip()">submit</button>
<script>
function tip() {
var bill = parseInt(document.getElementById("bill").value);
console.log(bill);
let yourTip = bill * 0.15;
let total = yourTip + bill;
console.log("Your tip is $" + yourTip);
console.log("Your total after the tip is $" + total);
}
</script>
Try this:
<style>
body {
text-align: center;
}
</style>
<body>
<input id="bill" placeholder ="How much was you meal?" />
<button onclick ="tip()">Calculate</button>
<h1 id="tip">Tip: $0</h1>
<h1 id="total">Total: $0</h1>
<script> let bill = document.querySelector("#bill")
function tip(){
let bill = document.getElementById('bill').value;
let billNum = parseInt(bill);
let yourTip = billNum * .15;
let total = yourTip + billNum;
document.getElementById('tip').innerHTML = "Tip: $" + yourTip;
document.getElementById('total').innerHTML = "Total: $" + total;
}
</script>
</body>
Let's break it down:
When you get the value of an input field, without specifying the type, JavaScript stores the value as a string. To turn that string into a number, you need to use parseInt(x), which tells the browser that the string is now a number, as you can't multiply a piece of text by a number. You can then multiply that number by the tip percentage.
Additionally, you also multiplied the tip by the bill. I added some styling, as well as using innerHTML instead of console.log() to display the tip and the total bill.
in python, you can do like this
print('Welcome to the tip calculator')
total_bill = float(input("What was the total bill? "))
what_percentage = float(input("What percentage tip would you like to give? "))
tip_percentage = (total_bill * what_percentage) / 100
total_cost = total_bill + tip_percentage
people = int(input("How many people to split the bill? "))
split_value = round(total_cost / people, 2)
print('Each person should pay' + str(split_value))

Values show together instead of as a new value

I did an exercise today in college, and it was a JavaScript program to calculate the average score of pupils in a test.
Here is my code:
<!DOCtype html>
<html>
<head>
<title>While loop</title>
</head>
<body>
<script>
//The total score of all pupils
var total = 0;
//The number of scores
var count = 1;
while (count <= 10) {
grade = prompt("Insert the grade:");
total = total + grade;
count++;
}
var average = +total / 10;
document.write("The average is " + average);
</script>
</body>
</html>
The values I put in are 10-100 going up in 10s. So I put in these 10 values "10, 20, 30, 40, 50, 60, 70, 80, 90, 100" And instead of getting the average, I'm getting all of these values side by side.
What am I doing wrong?
grade = prompt("Insert the grade:"); is the problem. The prompt is taking your input as a string, and in JS, adding two strings just concatenates the values. So parse your inputs:
grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number
Or use parseInt
grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);
FYI - all the numbers you're adding have to be integers - else it'll just end up as a string again, example:
10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010
Change
total = total + grade;
to
total = total + parseInt(grade);
when you write total = total + grade js concatenate total and grade as strings

I'm having trouble finishing a simple JS math game

I got my onclick function working, but the issue is that jQuery wasn't working for me for some reason, so I took it out, but I don't know how to disable the onclick without using jQuery: how can I disable the button's onclick and have it stay disabled if it is correct (and reset if it isn't correct? I also need to make it so that numOne and numTwo recalculate another random number if it is equal to the id of a disabled button, so I'm guessing I have change the do while loop I have to make sure that numTwo never equals numOne, but I'm not sure how to do all that.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lemon Squares - Grade 1 Edition</title>
</head>
<body id="bodyId">
<script type="text/javascript">
var button = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
var numbers = new Array();
for (var i=0; i<16; i++)
{
var randomNumber = Math.floor(Math.random()*9);
numbers[i] = document.createElement("button");
numbers[i].innerHTML = button[randomNumber];
numbers[i].setAttribute("type", "button");
numbers[i].setAttribute("id", button[i]);
numbers[i].setAttribute("onclick", "onClick('" + button[randomNumber] + "')");
numbers[i].setAttribute("value", button[randomNumber]);
document.getElementById("bodyId").appendChild(numbers[i]);
if (i == 3 || i == 7 || i == 11)
{
document.write("<br>");
}
}
var numOne = (Math.ceil(Math.random()*15)).toString();
var numTwo = (Math.ceil(Math.random()*15)).toString();
do
{
numTwo = Math.ceil(Math.random()*15).toString();
}
while (numTwo == numOne);
var numberOne = document.getElementById(numOne).value;
var numberTwo = document.getElementById(numTwo).value;
var answer = parseInt(numberOne) + parseInt(numberTwo);
var total = 0
function onClick(x)
{
x = parseInt(x);
total += x;
if (total > answer)
{
alert("Sorry, try again.")
total = 0
}
else if(total == answer)
{
alert("Congratulations, you did it!");
total = 0
}
}
document.write("<br> Pick two numbers that add up to: " + answer);
</script>
</body>
</html>
i think you are going about this the wrong way.
the logic of the game is (if i understand correctly):
pick "1 to n"(n is the count of all available buttons/items) number of items randomly
get the sum of the selected items value and show to user
record and add up the user selected values until the goal is reached and keep track of the selected items by user is an a array
if the selected items sum is correct disable the selected (just add disabled attribute to the button) items and reaped from step 1 where n is the number of remaining items
so for your problem :
on every button click take these steps :
add the value to a array
get the sum of values in the array
compare the sum with the answer
if the sum is less than the answer do nothing and wait for the next click
if the sum is equal to the answer
disable the buttons in the array
clear the selected items array
create a new answer
if the sum is more than the answer clear the selected items array and start over
i hope this helps .

Categories

Resources