Logical problem when assigning value using JS

Asked

Viewed 55 times

0

As explained in the paragraph below the goal is to create a betting game, so far so good, the Odd bet works perfectly by adding the amount bet to the total of points but the same does not happen with the bet Par it simply assigns nothing (and the logical comparison is the same and even returning the message of the scope).

var quantidadeApostada;
    var totalDePontos;
    var sorteio;
    
    function validarJogada() {
        if (document.formulario.parOuImpar[0].checked == false && document.formulario.parOuImpar[1].checked == false) {
            alert("Por favor escolha entre par ou impar !");
            return false;
        }
    
        quantidadeApostada = parseInt(document.getElementById("valor").value);
        totalDePontos = parseInt(document.getElementById("totalDePontos").innerHTML);
    
        if(quantidadeApostada < 0 || quantidadeApostada > 30){
            alert("Por favor informe uma aposta valida, entre 1 a 30 !!");
            return false;
        }
    
        if(quantidadeApostada > totalDePontos){
            alert("Sua aposta esta maior que seu total de pontos !!!");
            return false;
        }
    
         sorteio = Math.floor(Math.random()* 30 + 1);
    
        validarSorteio(sorteio, quantidadeApostada, totalDePontos);
    }
    
    function  validarSorteio() {
    
        if (document.querySelector('input[name = parOuImpar]:checked').value === "Par" && sorteio%2 === 0){
            alert("O número sorteado foi : " +sorteio+" sendo ele um número PAR");
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        }
    
        if (document.querySelector('input[name = parOuImpar]:checked').value === "Impar" && sorteio%2 === 1){
            alert("O número sorteado foi : " +sorteio+" sendo ele um número IMPAR");
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        } else{
            totalDePontos = totalDePontos - parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        }
    }
    
    function  novaQuantidadeDePontos() {
        var pontosExibir = document.getElementById('pontos').value;
    
        document.getElementById("totalDePontos").innerText = pontosExibir;
    }
    
    
    novaQuantidadeDePontos();
<!DOCTYPE html> 
<html lang="pt-br"> 
<head>
  <meta charset="UTF-8">
  <title>exercicio-5</title>
  <link rel="stylesheet" href="CSS/folhaDeEstilo.css"> 
</head> 
<body>
  <p id="semAlinhamento">
    Vamos criar nosso primeiro jogo! O usuário começa o jogo com 100 pontos. Deve ser apresentado 2 radio buttons,
    com os valores par e impar, e um campo de texto valor da aposta. Após selecionar preencher todos os campos, o
    usuário deve clicar em um botão jogar, então o sistema deve sortear um número aleatório de 1 à 30, e verificar
    se este número é par ou impar. Caso o número seja de acordo com o que o usuário apostou, deve-se somar a
    quantidade de pontos apostados ao seus pontos globais, caso seja diferente deve-se subtrair este valor. <br>
    Não deve ser possível clicar no botão jogar: <br>
    Não deve ser aceito nada além de valores numéricos, maior que zero, no campo valor da aposta.
    O sistema deve apresentar ao usuário qual número foi sorteado e informa-lo se o número é par ou impar. <br>
    Não deve ser possível clicar no botão jogar
    Caso o usuário não possua ou tente apostar uma quantidade de pontos maior do que possui.
    Caso o usuário não informe em qual tipo de número quer apostar.
  </p>
  <form name="formulario">
    <fieldset id="campoFormulario">
      <p>Vamos brincar !!!</p>
      <p>Escolha uma opção entre Par ou Impar e então aposte uma quantidade de pontos!!</p>
      <p>Boa Sorte !!!</p>
      <h3 id="subTitulo">Seu número total de pontos é <span id="totalDePontos"></span></h3>
      <input type="hidden" value="100" id="pontos">
      <input type="radio" name="parOuImpar" value="Par" class="radios">Par
      <input type="radio" name="parOuImpar" value="Impar" class="radios">Impar <br>
      <label for="valor" id="valorDaAposta">Valor da aposta</label>
      <input type="number" id="valor" min="1" max="30"> <br>
      <button type="button" onclick="validarJogada()" id="botaoJogar"> Jogar</button>
    </fieldset>
  </form>
</body> 
</html>

2 answers

1


Face from what I’ve seen in your job validarSorteio() when I was a couple if, but just below there was another if with a else that made the value go back to the previous one. One if was undoing the other one. I just added one else if.

I hope that’s it:

var quantidadeApostada;
    var totalDePontos;
    var sorteio;
    
    function validarJogada() {
        if (document.formulario.parOuImpar[0].checked == false && document.formulario.parOuImpar[1].checked == false) {
            alert("Por favor escolha entre par ou impar !");
            return false;
        }
    
        quantidadeApostada = parseInt(document.getElementById("valor").value);
        totalDePontos = parseInt(document.getElementById("totalDePontos").innerHTML);
    
        if(quantidadeApostada < 0 || quantidadeApostada > 30){
            alert("Por favor informe uma aposta valida, entre 1 a 30 !!");
            return false;
        }
    
        if(quantidadeApostada > totalDePontos){
            alert("Sua aposta esta maior que seu total de pontos !!!");
            return false;
        }
    
         sorteio = Math.floor(Math.random()* 30 + 1);
    
        validarSorteio(sorteio, quantidadeApostada, totalDePontos);
    }
    
    function  validarSorteio() {
    
        if (document.querySelector('input[name = parOuImpar]:checked').value === "Par" && sorteio%2 === 0){
            alert("O número sorteado foi : " +sorteio+" sendo ele um número PAR");
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        }else if (document.querySelector('input[name = parOuImpar]:checked').value === "Impar" && sorteio%2 === 1){
            alert("O número sorteado foi : " +sorteio+" sendo ele um número IMPAR");
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        } else{
            totalDePontos = totalDePontos - parseInt(quantidadeApostada);
            document.getElementById('pontos').value = totalDePontos;
            novaQuantidadeDePontos();
        }
    }
    
    function  novaQuantidadeDePontos() {
        var pontosExibir = document.getElementById('pontos').value;
    
        document.getElementById("totalDePontos").innerText = pontosExibir;
    }
    
    
    novaQuantidadeDePontos();
<!DOCTYPE html> 
<html lang="pt-br"> 
<head>
  <meta charset="UTF-8">
  <title>exercicio-5</title>
  <link rel="stylesheet" href="CSS/folhaDeEstilo.css"> 
</head> 
<body>
  <p id="semAlinhamento">
    Vamos criar nosso primeiro jogo! O usuário começa o jogo com 100 pontos. Deve ser apresentado 2 radio buttons,
    com os valores par e impar, e um campo de texto valor da aposta. Após selecionar preencher todos os campos, o
    usuário deve clicar em um botão jogar, então o sistema deve sortear um número aleatório de 1 à 30, e verificar
    se este número é par ou impar. Caso o número seja de acordo com o que o usuário apostou, deve-se somar a
    quantidade de pontos apostados ao seus pontos globais, caso seja diferente deve-se subtrair este valor. <br>
    Não deve ser possível clicar no botão jogar: <br>
    Não deve ser aceito nada além de valores numéricos, maior que zero, no campo valor da aposta.
    O sistema deve apresentar ao usuário qual número foi sorteado e informa-lo se o número é par ou impar. <br>
    Não deve ser possível clicar no botão jogar
    Caso o usuário não possua ou tente apostar uma quantidade de pontos maior do que possui.
    Caso o usuário não informe em qual tipo de número quer apostar.
  </p>
  <form name="formulario">
    <fieldset id="campoFormulario">
      <p>Vamos brincar !!!</p>
      <p>Escolha uma opção entre Par ou Impar e então aposte uma quantidade de pontos!!</p>
      <p>Boa Sorte !!!</p>
      <h3 id="subTitulo">Seu número total de pontos é <span id="totalDePontos"></span></h3>
      <input type="hidden" value="100" id="pontos">
      <input type="radio" name="parOuImpar" value="Par" class="radios">Par
      <input type="radio" name="parOuImpar" value="Impar" class="radios">Impar <br>
      <label for="valor" id="valorDaAposta">Valor da aposta</label>
      <input type="number" id="valor" min="1" max="30"> <br>
      <button type="button" onclick="validarJogada()" id="botaoJogar"> Jogar</button>
    </fieldset>
  </form>
</body> 
</html>

Explaining

The first if of the function checks whether the even option is selected, if nothing is happening. Already the second if has an Else, so when it was selected the option for it entered in the first and when it went pro second gave false because it was not odd that it was selected and ended up executing the Else, which was exactly what subtracts going back to the normal value.

Can you understand? Then being executed the first if and then the second if Else. Then was added the value of the bet and then entered into the E-l that nullified it.

  • Guy worked perfectly , but you could explain to me how one if nullified the other ? Why so one condition is different from the other

  • No problem. I’ll explain in the above answer. Just 1 minute.

  • I tried to explain there, I hope you understand. Thanks! D

  • Thank you very much. Valews

0

You can simplify the comparison for a if else thus:

In the form change the values to 0 and 1

<input type="radio" name="parOuImpar" value="0" class="radios">Par
<input type="radio" name="parOuImpar" value="1" class="radios">Impar

In the script compare the value input selected with variable module sorteio

var valInput = document.querySelector('input[name = parOuImpar]:checked').value;
var modSorteio = sorteio%2;

      if (valInput == modSorteio ){
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
      } else{
            totalDePontos = totalDePontos - parseInt(quantidadeApostada);
      }
      alert("O número sorteado foi : " +sorteio+" sendo ele um número "+msg);
      document.getElementById('pontos').value = totalDePontos;
      novaQuantidadeDePontos();

Total code working

var quantidadeApostada;
    var totalDePontos;
    var sorteio;
    var msg;
    
    function validarJogada() {
        if (document.formulario.parOuImpar[0].checked == false && document.formulario.parOuImpar[1].checked == false) {
            alert("Por favor escolha entre par ou impar !");
            return false;
        }
    
        quantidadeApostada = parseInt(document.getElementById("valor").value);
        totalDePontos = parseInt(document.getElementById("totalDePontos").innerHTML);
    
        if(quantidadeApostada < 0 || quantidadeApostada > 30){
            alert("Por favor informe uma aposta valida, entre 1 a 30 !!");
            return false;
        }
    
        if(quantidadeApostada > totalDePontos){
            alert("Sua aposta esta maior que seu total de pontos !!!");
            return false;
        }
    
         sorteio = Math.floor(Math.random()* 30 + 1);
    
        validarSorteio(sorteio, quantidadeApostada, totalDePontos);
    }
    
    function  validarSorteio() {

      if (sorteio%2===0){
        msg="Par";
      }else{
         msg="Impar";
      }
      
      var valInput = document.querySelector('input[name = parOuImpar]:checked').value;
      var modSorteio = sorteio%2;
      
      if (valInput == modSorteio ){
            totalDePontos = totalDePontos + parseInt(quantidadeApostada);
      } else{
            totalDePontos = totalDePontos - parseInt(quantidadeApostada);
      }
      alert("O número sorteado foi : " +sorteio+" sendo ele um número "+msg);
      document.getElementById('pontos').value = totalDePontos;
      novaQuantidadeDePontos();
   }
    
    function  novaQuantidadeDePontos() {
        var pontosExibir = document.getElementById('pontos').value;
    
        document.getElementById("totalDePontos").innerText = pontosExibir;
    }
    
    
    novaQuantidadeDePontos();
        <form name="formulario">
            <fieldset id="campoFormulario">
                <p>Vamos brincar !!!</p>
                <p>Escolha uma opção entre Par ou Impar e então aposte uma quantidade de pontos!!</p>
                <p>Boa Sorte !!!</p>
                <h3 id="subTitulo">Seu número total de pontos é <span id="totalDePontos"></span></h3>
                <input type="hidden" value="100" id="pontos">
                <input type="radio" name="parOuImpar" value="0" class="radios">Par
                <input type="radio" name="parOuImpar" value="1" class="radios">Impar <br>
                 <label for="valor" id="valorDaAposta">Valor da aposta</label>
                <input type="number" id="valor" min="1" max="30"> <br>
                <button type="button" onclick="validarJogada()" id="botaoJogar">Jogar</button>
            </fieldset>
        </form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.