1

Estou tentando criar um quiz simples mas não domino muito programação.

A intenção é que, quando o usuário marcar uma resposta e clicar no botão, já apareça uma div mostrando se está certo ou errado.

Inicialmente, eu fiz com o um alert em javascript e tinha dado certo, depois alterei pra aparecer as divs, começou a dar problema. Acredito que o motivo seja porque ele carrega a pagina, daí some, é isso mesmo? Como resolver este problema?

Segue o código:

     function fSubmit() {
       var correctanswer = document.getElementById("oi");
       if (correctanswer.checked == true) {
         document.getElementById("div-certo").style.display = 'block';
       } else {
         document.getElementById("div-errado").style.display = 'block';
       }
     }
    #div-certo {
      display: none;
      width: 300px;
      height: 200px;
      background: green;
    }
    #div-errado {
      display: none;
      width: 300px;
      height: 200px;
      background: yellow;
    }
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>

</head>

<body>

  <form>
    lalalalalala
    <input name="radio" type="radio" value="errado1" id="errado1">
    <input name="radio" type="radio" value="errado2" id="errado2">
    <input name="radio" type="radio" value="certo" id="oi">
    <input name="radio" type="radio" value="errado3" id="errado3">
    <input type="submit" id="btnsubmit" onClick="fSubmit()" />
  </form>

  <div id="div-certo">certo</div>

  <div id="div-errado">errado</div>

</body>

</html>

2 Respostas 2

2

Ola,Teste este código, ele não dava certo antes porque o formulário quando era submitado ele voltava para seu inicio, ou seja, ele atualizava a página, então a solução foi colocar um event no form que nao deixa ele ser atualizado, ele insere as div sem atualizar a pagina inteira

function fSubmit() {

  var correctanswer = document.getElementById("oi");
  var form = document.getElementById('form');

  form.addEventListener('submit', function(event) {
    if (correctanswer.checked) {
      document.getElementById("div-certo").style.display = 'block';
      document.getElementById("div-errado").style.display = 'none';

    } else {
      document.getElementById("div-certo").style.display = 'none';
      document.getElementById("div-errado").style.display = 'block';
    }
    event.preventDefault();
  });

}
    #div-certo {
      display: none;
      width: 300px;
      height: 200px;
      background: green;
    }
    #div-errado {
      display: none;
      width: 300px;
      height: 200px;
      background: yellow;
    }
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
</head>

<body>

  <form id="form">
    lalalalalala
    <input name="radio" type="radio" value="errado1" id="errado1">
    <input name="radio" type="radio" value="errado2" id="errado2">
    <input name="radio" type="radio" value="certo" id="oi">
    <input name="radio" type="radio" value="errado3" id="errado3">
    <input type="submit" id="btnsubmit" onClick="fSubmit()" />
  </form>

  <div id="div-certo">certo</div>
  <div id="div-errado">errado</div>

</body>

</html>

Espero ter ajudado!

3
  • Guilherme, inseri seu código no snippet, assim, é possivel não só visualizá-lo, mas também testá-lo aqui no site. :)
    – user28595
    30/03/2016 às 14:37
  • Ok, muito obrigado, sou novo por aqui, não conheço todos os recursos, Grato! 30/03/2016 às 14:38
  • funcionou certinho! Obrigada!!! 30/03/2016 às 14:51
0

Estou com outros problemas agora. Precisava de 4 formulários e eles está dando conflito com outras respostas. Esse é o link http://juadri.com.br/cursos/quiz.html

E o código

<!DOCTYPE html>
<html lang="pt-br" id="Pos">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="css/styleQuiz.css" type="text/css" />
<link rel="stylesheet" href="css/animate.css" type="text/css" />
</head>

<body>

<div id="mainQuiz">
    <div class="contentQuiz">
        <div class="boxQuiz">
            <div class="numQuiz">1</div>
            <div class="boxContentQuiz boxEsq">
            Assinale o que uma criança de 4 anos provavelmente NÃO consegue fazer com autonomia e facilidade, apesar de poder haver raras exceções:
            </div>
            <div class="boxContentQuiz boxDir">
              <form id="form01">
                <label><input name="radio" type="radio" value="resposta01" id="resposta01">Consegue pular com os dois pés e com um pé só</label>
                <label><input name="radio" type="radio" value="resposta02" id="resposta02">Começa a fazer amigos e entender o que é a amizade</label>
                <label><input name="radio" type="radio" value="resposta03" id="resposta03">Imita os adultos a sua volta e até os seus colegas</label>
                <label><input name="radio" type="radio" value="resposta04" id="resposta04">Escreve e lê convencionalmente</label>
                <input type="submit" id="btnsubmit" onClick="fSubmit()" value="" />
              </form>
            </div>
        </div>
    </div>

<div class="contentQuiz">
        <div class="boxQuiz">
            <div class="numQuiz">2</div>
            <div class="boxContentQuiz boxEsq">
            Assinale o que uma criança de 4 anos provavelmente NÃO consegue fazer com autonomia e facilidade, apesar de poder haver raras exceções:
            </div>
            <div class="boxContentQuiz boxDir">
              <form id="form02">
                <label><input name="radio" type="radio" value="resposta05" id="resposta05">Consegue pular com os dois pés e com um pé só</label>
                <label><input name="radio" type="radio" value="resposta06" id="resposta06">Começa a fazer amigos e entender o que é a amizade</label>
                <label><input name="radio" type="radio" value="resposta07" id="resposta07">Imita os adultos a sua volta e até os seus colegas</label>
                <label><input name="radio" type="radio" value="resposta08" id="resposta08">Escreve e lê convencionalmente</label>
                <input type="submit" id="btnsubmit" onClick="fSubmit()" value="" />
              </form>
            </div>
        </div>
    </div>

</div>
  <div id="div-certo">
    <div class="divCertoConteudo animated bounceInUp">
      RESPOSTA CORRETA <br>
      <a href=""><img src="imgs/btProxima.png"></a>
    </div>
  </div>
  <div id="div-errado">
  <div class="divErradoConteudo animated bounceInUp">
  RESPOSTA INCORRETA<br>
      <a href=""><img src="imgs/btProxima.png"></a>
  </div>
  </div>

<script type="text/javascript">
function fSubmit() {


  var form = document.getElementById('form01');
  var correctanswer = document.getElementById("resposta02");

  form.addEventListener('submit', function(event) {
    if (correctanswer.checked) {
      document.getElementById("div-certo").style.display = 'block';
      document.getElementById("div-errado").style.display = 'none';

    } else {
      document.getElementById("div-certo").style.display = 'none';
      document.getElementById("div-errado").style.display = 'block';
    }
    event.preventDefault();
  });


  var form = document.getElementById('form02');
  var correctanswer = document.getElementById("resposta07");

  form.addEventListener('submit', function(event) {
    if (correctanswer.checked) {
      document.getElementById("div-certo").style.display = 'block';
      document.getElementById("div-errado").style.display = 'none';

    } else {
      document.getElementById("div-certo").style.display = 'none';
      document.getElementById("div-errado").style.display = 'block';
    }
    event.preventDefault();
  });

}
</script>



</body>
</html>

Outra coisa se puderem me ajudar, quando eu clicar no botão da div "Resposta incorreta" eu gostaria de esconder aquela div e quando eu clicar no botão da div "resposta correta" aparecer o formulário seguinte. Pensei em fazer isso com ancora mas não sei se teria algo melhor.

Obrigada desde já.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .