Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
javascript button heads or tails not giving correct output

I'm new to javascript and I've created a program that chooses heads or tails at random and has the user click one of two buttons (one labeled heads, the other tails) and it will show whether they guessed correctly and keep track of their wins/losses. I got it to out "You guessed [heads/tails]" but the second half always gives "you are incorrect". Plus it won't show the wins/losses counter.

HTML (file named HeadsTails):

<!DOCTYPE html>
<html>
    <head>
        <title>Project 2</title>
    </head>
    <body>
        <script src = "jasc.js" defer></script>

        <p>Guess heads or tails:</p>
        <form name = 'headsTails'>
            <input type ='button' value = 'heads' onclick = "headsChoice();" />
            <input type ='button' value = 'tails' onclick = "tailsChoice();" />
        </form>
        <div id = 'output'></div>

    </body>
</html>

Javascript (file named jasc):

const coin = ['heads', 'tails'];
const flip = Math.floor(Math.random() * coin.length);

const form = document.forms.headsTails;
const output = document.getElementById('output');

const heads = document.getElementById('heads');
heads.addEventListener('click', headsChoice);

const tails = document.getElementById('tails');
tails.addEventListener('click', tailsChoice);

let win = 0;
let loss = 0;

function headsChoice(e){
    if (flip == coin[0]) {
        output.textContent = 'You guessed heads, you were correct!';
        win++;
    } //if end
    else {
        output.textContent = 'You guessed heads, you were incorrect.';
        loss++;
    } //else end
    output.textContent = 'Wins: ${win} || Losses: ${loss}';
} //headsChoice end

function tailsChoice(e){
    if (flip == coin[1]) {
        output.textContent = 'You guessed tails, you were correct!';
        win++;
    } //if end
    else {
        output.textContent = 'You guessed tails, you were incorrect.';
        loss++;
    } //else end
    output.textContent = 'Wins: ${win} || Losses: ${loss}';
} //tailsChoice end
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There are two issues.

  1. flip is equal to zero or one, but never the string you're comparing it against.
if (flip == coin[0])

The fix:

if (coin[flip] == coin[0])
  1. You need to re-flip the coin, or you'll always be checking against the one and only flip. Simple fix is to add a reflip function and run it before each heads or tails choice.

Demo

const coin = ['heads', 'tails'];
let flip = Math.floor(Math.random() * coin.length);

const form = document.forms.headsTails;
const output = document.getElementById('output');

const heads = document.getElementById('heads');
heads.addEventListener('click', headsChoice);

const tails = document.getElementById('tails');
tails.addEventListener('click', tailsChoice);


let win = 0;
let loss = 0;

function reflip() {
  flip = Math.floor(Math.random() * coin.length);
}

function headsChoice(e) {
  reflip()
  if (coin[flip] === coin[0]) {
    output.textContent = 'You guessed heads, you were correct!';
    win++;
  } //if end
  else {
    output.textContent = 'You guessed heads, you were incorrect.';
    loss++;
  } //else end
  output.textContent = 'Wins: ${win} || Losses: ${loss}';
} //headsChoice end

function tailsChoice(e) {
  reflip()
  if (coin[flip] === coin[1]) {
    output.textContent = 'You guessed tails, you were correct!';
    win++;
  } //if end
  else {
    output.textContent = 'You guessed tails, you were incorrect.';
    loss++;
  } //else end
  output.textContent = 'Wins: ${win} || Losses: ${loss}';
} //tailsChoice end
<p>Guess heads or tails:</p>
<form name='headsTails'>
  <input type='button' value='heads' onclick="headsChoice();" />
  <input type='button' value='tails' onclick="tailsChoice();" />
</form>
<div id='output'></div>

jsFiddle

about 4 years ago · Juan Pablo Isaza Relatório

0

Your getElementById methods aren't finding any elements because there are no elements with an id of either 'heads' or 'tails'.

try this:

<!DOCTYPE html>
<html>
<head>
<title>Project 2</title>
</head>
<body>
<script src = "jasc.js" defer></script>
<p>Guess heads or tails:</p>
<form name="headsTails">
  <input id="heads" type="button" value="heads" onclick="headsChoice();"/>
  <input id="tails" type="button" value="tails" onclick="tailsChoice();"/>
</form>
<div id = 'output'></div>
</body>
</html>
about 4 years ago · Juan Pablo Isaza Relatório

0

The second part of the code is not correctly defined. Interpolation of the variable in a string is a little bit tricky.

The simple single quotes cant replace a variable value in the string, there has to be this type of qoutation (`).

let win = 0;
let loss = 0;

function headsChoice(e){

 output.textContent = `Wins: ${win} || Losses: ${loss}`;
} //headsChoice end

function tailsChoice(e){

   output.textContent = `Wins: ${win} || Losses: ${loss}`;
} //tailsChoice end
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda