1
I’m having a problem not knowing how to identify if the user has selected an option type=radio
.
Follows the code:
let nComputador = "";
let nJogador = "";
//let minhaEscolha = document.querySelector("input[type='radio']:checked").value;
function sortear(max) {
return Math.floor(Math.random() * max);
};
let play = document.getElementById("jogar").addEventListener('click', function() {
let minhaEscolha = document.querySelector("input[type='radio']:checked").value;
if (minhaEscolha === null) {
return alert("escolha uma opção!")
}
nJogador = parseFloat(document.querySelector("#meuNumero").value);
nComputador = sortear(10);
if (isNaN(nJogador)) {
return alert("digite um numero");
}
let soma = ((nJogador + nComputador) % 2 === 0) ? "par" : "impar";
let resultado = (soma == minhaEscolha) ? alert("ganhei") : alert("computador ganhou");
console.log(nComputador, nJogador, minhaEscolha, soma);
});
<body>
<h1>
jogo do par ou impar
</h1>
<p>
Digite um número de 0 a 10:
<input type="number" id="meuNumero" min="0" max="10">
<label><input type="radio" name="escolha" value="par">Par</label>
<label><input type="radio" name="escolha" value="impar">Impar</label>
</p>
<button id="jogar">Jogar</button>
</body>
That one if
shouldn’t work?
if (minhaEscolha === null) {
return alert("escolha uma opção!")
}
I got it, I checked the code I had done looked like it, but right after if(!myChoose) I had put an Else to get value, this interferes?
– Patrick Eidrian
@Patrickeidrian As inside the
if (!minhaEscolha)
has areturn
, if you enter theif
it leaves the function, then theelse
in this case it makes no difference. see here: https://ideone.com/84lyHS– hkotsubo
I didn’t know that part of
return
, and on theparseFloat
I usually put because the user knows, I don’t know what he can try. thank you– Patrick Eidrian
@Patrickeidrian
parseInt("2.5")
will round to2
, then you decide what’s best in your case, accept2.5
(that will never be equal, for the rest of the division is0.5
), or round automatically withparseInt
.– hkotsubo
is really better the
parseInt
, another valuable tip (y)– Patrick Eidrian