Sorry to bother all of you. I know, this question has been asked multiple times. However, I just couldn't fix my problem.
So, I've been trying to create a tennis scoring system that shows the score when you click one of two buttons, the win button or the lose button. I have a button where they can add their name to the scoring system. When one player wins two sets the match is over. I then try to print their name saying, ____ won the match. When I try using the variable that printed their name before I get something that says: [objectHTMLButtonElement]. I've been trying for a long time to fix this and I don't know how to.
Here is the code:
document.getElementById("youName").onclick = function() {
var youName = prompt("Enter your name");
document.getElementById("youOutput").innerHTML = youName + ":";
}
let points = 0;
function win() {
points += 1;
document.getElementById("points").innerHTML = points;
if (points == 2) {
document.getElementById("finish").innerHTML = youName + " won the match";
}
}
<button id="youName">Your name</button>
<p id="youOutput"></p>
<button onclick="win()">Won the point</button>
<p id="points"></p>
<p id="finish"></p>
Thanks in advance.
Try to declare yourName in a global context
let yourName = null;
document.getElementById("youName").onclick = function () {
yourName = prompt("Enter your name");
document.getElementById("youOutput").textContent = `${yourName}`;
};
let points = 0;
function win() {
points += 1;
document.getElementById("points").innerHTML = points;
if (points == 2) {
document.getElementById(
"finish"
).textContent = `${yourName} won the match`;
}
}
Related
I am currently completing a project and have come across an error in my coding.
I have a button which calls a JS prompt box asking to enter an integer between 0 and 9.
This number is then used as a game where 3 random integers from 0 and 9 appear every second and when you click on the matching number your score increases.
This is my code so far:
<script>
function chooseNum()
{
var txt;
var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("chosen").innerHTML = txt;
}
</script>
I want to know exactly how to display random integers in a range from 0 and 9.
Is a code like this on the right track?
<script>
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*9);
$('#number1').html(rand);
}
</script>
Can anyone point me in the right direction?
Cheers.
var txt;
function chooseNum()
{
var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("chosen").innerHTML = txt;
}
chooseNum() ;
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()* 9 + 1);
$('#number1').html(rand);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="chosen"></p>
<p id="number1"></p>
I'm just learning javascript and my project is to create a web page with the following elements: An h2 header, two img elements, an input box, and a button element. When the page loads, Dice.getURL is called twice to get the URL for the 1-dot die, and the jQuery.attr() function is used to display the images when the page loads: When the user enters a target number and clicks Roll 'em!, the images are updated die-namically and the results displayed in a div on the page.
I've got the basics down but I have no idea how to do the rest of this stuff. I've been looking online but haven't found what I needed. I hope you guys can be what I need:
The main issue that I have is that the numRolls variable is not keep track of how many times the do/while loop runs through. I am also confused on how to keep track of the dice rolls via images so it displays the correct output when the "solution is found"
Here is a link to my jsfiddle: https://jsfiddle.net/0088v6nt/3/
HTML
<!Doctype html>
<body>
<h2>Roll Number</h2>
<img id="dice1" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<img id="dice2" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<p>Enter target number:</p>
<input type="text" id="num"><br><br>
<button id="R">Roll 'em!</button>
<br><br>
<div id="time"></div>
</body>
JavaScript
//define a Dice object, properties and methods
var Dice = {
sides: 6,
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
},
rollDice: function() {
var diceTotal = 0;
diceTotal += this.rollDie($('#dice1'));
diceTotal += this.rollDie($('#dice2'));
return diceTotal;
},
URL_prefix: "http://dave-reed.com/book3e/Images/",
getURL: function(n) {
//return the URL for an n-dot die
return this.URL_prefix + "die" + n + ".gif";
}
};
//top-level function
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
var numRolls = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
function getRoll () {
var number = parseFloat($("#num").val());
var numRolls = roll_number(number);
$("#time").text( "You rolled " + number + " in " + numRolls + " rolls");
}
$(document).ready(function(){
$("#R").on("click", getRoll);
//$("#roll").on("click", Dice.getURL);
});
Thank you again!
-Kron
There's two issues with your code. First die1 and die2 are never set because Dice.rollDie doesn't return a value. Updating the function to return the value of the die fixes this:
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
return rolledValue;
},
Second, the while loop currently only set to keep running while the sum matches the total, instead it should keep running while it doesn't match the total. It should look like instead:
while(die1 + die2 !== n);
This can lead to infinite loops if you pass a bad value to n (such as null, or anything greater than 12), so be careful
https://jsfiddle.net/0088v6nt/4/
You're setting the counter to zero every time the roll_number function is called i fixed it by moving the counter variable outside the function scope so it's not being reset all the time..
var numRolls = 0;
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
https://jsfiddle.net/0088v6nt/5/
I'm having trouble creating a Blackjack program to display in an HTML page using an external Javascript file.
I don't need to label my cards, and I've created a dealer that will always be between 17-21 in score.
I'm unsure of what parts of my code is completely wrong and what needs a bit of tweaking. I believe I've done something that has broken the program.
EDIT: I've edited some of the fixes that many of you have helped with, an error I get when running the program is that if I do use an alert to display the score/outcome, the alert does not appear when running.
My goal is to display my the score/cards from my Javascript code into my HTML code which looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blackjack</title>
<link rel="stylesheet" type="text/css" href="CSSedit.css">
</head>
<body>
<script type="text/javascript" src="Blackjack.js">
</script>
<h1>Javascript Blackjack</h1>
<p>Player's Hand: </p>
<br>
<p>Dealer's Score: </p>
<p>Player's Score: </p>
<br>
<p>Game Results: </p>
</body>
</html>
My javascript code:
//function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
//function that returns dealers hand between 17-21
var dealerhand = function(x, y) {
cardDealer = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardDealer;
}
//declaring variables
var card1 = deal();
var card2 = deal();
var dealer = dealerhand();
var x = 17;
var y = 21;
//retrieving the value of the cards from the deal function
var getValue = function(card) {
if(card % 13 === 0 || card % 13 === 11 || card % 13 === 12){
return 10;
}
if(card % 13 === 1){
return 11;
}
else{
return card % 13;
}
}
//scoring the cards dealt and determining the outcome
//using the if and else if statements
function score() {
if ((getValue(card1) + getValue(card2)) > 22){
return "Busted!";
}
else if (getValue(cardDealer) > getValue(card1) + getValue(card2)){
return "You lose!";
}
else if (getValue(cardDealer) === getValue(card1) + getValue(card2)){
return "Draw!";
}
else{
return getValue(card1) + getValue(card2);
}
}
//Need to display results onto HTML page
//alert("You have card " + card1 + " / " + card2 +
// " Score: " + score(card1, card2);
You have a syntax error on your deal function
//function that returns dealers hand between 17-21
var dealerhand = function(17, 21) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD; //should be return card;
}
Use the console in your browser (accessible through dev tools) to help spot errors in your application, errors like this show up bright as day.
There is a syntax error on line 14:
var dealerhand = function(17, 21) {
...
You can only pass variables as arguments to a function and 17 and 21 are not variables. An easy fix would be:
var a = 17;
var b = 21;
var dealerhand = function(a, b) {
...
Hopefully ES6's argument defaults will clear some confusion in this area.
Edit:
You have another error on line 41:
if (getValue(card1) + getValue(card2) > 22{
Should be
if ((getValue(card1) + getValue(card2)) > 22) { ... }
Edit 2:
An another one. Functions should be declared before using references in the variables and thus these two functions should come before your declaring variables comment.
// function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
// function that returns dealers hand between 17-21
var dealerhand = function(a, b) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD;
}
I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.
I have been trying to do a simple game where you try to get the right number as the random number. If you win, you get 1 point. But I wasn't able to give that point. Here is what i have done :
<html>
<head>
<title>Luck Game</title>
<script>
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
var points = 0;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
</head>
<body>
<input id="input"></input>
<p id="Answer"></p>
<button onClick="onClick()"></button>
<p id="WIN?"></p>
<p id="points"></p>
</body>
But the "points = points + 1" is not working !
what is wrong ? please help me .
You should declare your var points outside click function. E.g :
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;
}
else{
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
So the counter will be saved somewhere else without being resetted everytime function procs.
The way you've written it, points is a variable local to the onClick() function so it will get reset to zero each time the function is called. If you pull the initialization of points out of onClick() then you will be able to safely increment its value:
<script>
var points = 0;
function onClick(){
var number = Math.floor(Math.random()*10);
var usernumber = document.getElementById("input").value ;
document.getElementById("Answer").innerHTML = number ;
document.getElementById("points").innerHTML = "Points in your account : " + points;
if(usernumber == number){
document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points++;
} else {
document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
}
}
</script>
Declare var points outside function:
var points = 0;
function onClick(){
...
}