Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda