Verify correct answer

Asked

Viewed 174 times

0

Good afternoon, I am making a form of simple questions and answers. I would like to know how to case the answer is to wrong, show the correct alternative in Alert.

$(document).ready(function() {


  $("input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      alert("Errado");
    }
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3>
  <p>Primeira pergunta de teste:</p>
</h3>

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1
<br>
<input name="r" type="radio" class="ace" value="S"> Resposta certa
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 2
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 3

4 answers

5


The texts, which are the answers, come next from the element, so in DOM you can use the nextSibling (in jQuery in the API has the .next(), but is not the same thing), then it would look something like:

 $('[name="r"][value="S"]').get(0).nextSibling.textContent;

This way you will pick up the following text of the desired element (in case the element with the correct answer), example:

$(document).ready(function() {


  $("input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      var resposta = $('[name="r"][value="S"]').get(0).nextSibling.textContent;
      alert("Errado, a resposta correta seria: " + resposta);
    }
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3>
  <p>Primeira pergunta de teste:</p>
</h3>

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1
<br>
<input name="r" type="radio" class="ace" value="S"> Resposta certa
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 2
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 3

However you can simplify and even avoid accidents by creating elements to separate the answers instead of using <br>, this way you can have several questions on the same page, example:

$(document).ready(function() {


  $(".resposta input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      console.log($(this).parents('.pergunta').find('[name="r"][value="S"]').parent().get(0))
      var resposta = $(this).parents('.pergunta').find('[name="r"][value="S"]').parent().text().trim();
      alert("Errado, a resposta correta seria: " + resposta);
    }
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="pergunta">
    <h3>
      <p>Primeira pergunta de teste:</p>
    </h3>

    <div class="resposta">
         <input name="r" type="radio" class="ace" value="N"> Resposta errada 1
    </div>
    <div class="resposta">
         <input name="r" type="radio" class="ace" value="S"> Resposta certa
    </div>
    <div class="resposta">
        <input name="r" type="radio" class="ace" value="N"> Resposta errada 2
    </div>
    <div class="resposta">
        <input name="r" type="radio" class="ace" value="N"> Resposta errada 3
    </div>
</div>

<div class="pergunta">
    <h3>
      <p>Segunda pergunta de teste:</p>
    </h3>

    <div class="resposta">
         <input name="r" type="radio" class="ace" value="N"> Pedro Álvares Cabral
    </div>
    <div class="resposta">
         <input name="r" type="radio" class="ace" value="S"> Graham Bell
    </div>
    <div class="resposta">
        <input name="r" type="radio" class="ace" value="N"> George Washington
    </div>
    <div class="resposta">
        <input name="r" type="radio" class="ace" value="N"> Thomas Edison
    </div>
</div>

  • Why are these characters appearing? https://prnt.sc/p8c8mn

  • @James here did not appear any character so, test on the RUN button above, the two examples (the second is better) ... these characters seem another problem outside of this script, if you have how to put online for me to test or send the file would make it easy to identify, but I repeat, the problem is not in the answer script, it is elsewhere.

2

First, I have to say that your HTML did not make much sense and seems to be poorly planned. You have a list that is not listed; you have 5 answer options for each question, but in fact you only have 2, because what is considered will be the value of the element input[type=radio]. That is, the text "associated" with input will make no difference to the semantics. When you want to associate a text to the field, you should use the label.

It should be something like this:

<div id="pergunta-1">
  <h1>Enunciado da pergunta</h1>
  <ul>
    <li>
      <input id="opcao-1" type="radio" name="respostas-1" value="1" data-correta="N">
      <label for="opcao-1">Opção 1 errada</label>
    </li>
    <li>
      <input id="opcao-2" type="radio" name="respostas-1" value="2" data-correta="N">
      <label for="opcao-2">Opção 2 errada</label>
    </li>
    <li>
      <input id="opcao-3" type="radio" name="respostas-1" value="3" data-correta="S">
      <label for="opcao-3">Opção 3 errada</label>
    </li>
    <li>
      <input id="opcao-4" type="radio" name="respostas-1" value="4" data-correta="N">
      <label for="opcao-4">Opção 4 errada</label>
    </li>
    <li>
      <input id="opcao-5" type="radio" name="respostas-1" value="5" data-correta="N">
      <label for="opcao-5">Opção 5 errada</label>
    </li>
  </ul>
</div>

See that the value of the options is a value that identifies that option. In this example I used values from 1 to 5 representing the option ids, but it could be any value that identifies that option in that question. Control of which option is correct has been passed to the attribute data-correta.

So, with Javascript, it would be:

$("input[type=radio]").on("change", function() {
  if (this.dataset.correta === 'N') {
    // Exibe a resposta correta:
    alert($(`input[name="${this.name}"][data-correta="S"] + label`).text());
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<fieldset id="pergunta-1">
  <h1>Enunciado da pergunta</h1>
  <ul>
    <li>
      <input id="opcao-1" type="radio" name="respostas-1" value="1" data-correta="N">
      <label for="opcao-1">Opção 1 errada</label>
    </li>
    <li>
      <input id="opcao-2" type="radio" name="respostas-1" value="2" data-correta="N">
      <label for="opcao-2">Opção 2 errada</label>
    </li>
    <li>
      <input id="opcao-3" type="radio" name="respostas-1" value="3" data-correta="S">
      <label for="opcao-3">Opção 3 correta</label>
    </li>
    <li>
      <input id="opcao-4" type="radio" name="respostas-1" value="4" data-correta="N">
      <label for="opcao-4">Opção 4 errada</label>
    </li>
    <li>
      <input id="opcao-5" type="radio" name="respostas-1" value="5" data-correta="N">
      <label for="opcao-5">Opção 5 errada</label>
    </li>
  </ul>
</fieldset>

Where input[name="${this.name}"][data-correta="S"] will seek the correct answer to that question and the + label selects the label associated with input, displaying your text. Another option would be to select the label from the value of for through the id of the right option.

As the questions will have a group of answers that will be independent of the options of the other questions, it is convenient to use the <fieldset> to group the semantically related elements within the form.

  • Dataset + label .... very elegant! Just missed to put inside a haha fieldset. And look what mass, the old.... https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/radiogroup

  • 1

    @hugocsl and even it would be interesting to put each question inside a fieldset to define the independence between them, even though they belong to the same form.

2

Guy just put inside the condition to even clicking the wrong one he marks the right one. So if you mark the wrong one he alerts you and makes a :checked in the input with name="r" value="S" kind of $('[name="r"][value="S"]').prop("checked", true);. That way you ensure that only the input with value="S" belonging to the radio-group of name="r" will be tagged (Thanks @Andersoncarloswoss for the remark)

inserir a descrição da imagem aqui

$(document).ready(function() {

    $("input[type='radio']").click(function() {
        var marcado = this.value;

        if (marcado == "S") {
            alert("Correto");
        } else {
            alert("Errado");
            $('[name="r"][value="S"]').prop("checked", true);
        }
    });

});
[value="S"]:checked {
    transform:scale(2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3>
    <p>Primeira pergunta de teste:</p>
</h3>

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1
<br>
<input name="r" type="radio" class="ace" value="S"> Resposta certa
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 2
<br>
<input name="r" type="radio" class="ace" value="N"> Resposta errada 3

  • Instead of $('[value="S"]') better do $('[name="r"][value="S"]') to ensure that you take the correct option of the same question (changing r dynamically according to the question), considering that there may be multiple questions on the page. And I have to say it’s weird having four radios with the same value :x

  • @Andersoncarloswoss very well observed, I even made an Edit in response ;)

  • 1

    But it is not to mark the correct answer if it marks the wrong one. It only appears in Alert the text corresponding to the correct answer.

  • @Tiago in this case I only answered if the text followed by Radio was inside a tag, like this: <input name="r" type="radio" class="ace" value="S"> <span>Right answer</span> <br> I could catch it. In the meantime, it seems that William’s answer will suit you at this point.

  • @hugocsl although nextSibling initially meets the second example of my answer shows how to do if you need multiple questions on the same page.

  • 1

    @Guilhermenascimento I’m reading it right now rss, really the way you structured HTML helps a lot to control things. This should happen a lot when "designer" does HTML, and then passes to Dev. do the code haha

Show 1 more comment

0

I made a template in Javascript Puro, I know you didn’t ask :) There are other ways to do more this is also very practical and very simple.

    var ace = window.document.getElementsByName('r');

    ace[0].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })
    ace[1],
    ace[2].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })
    ace[3].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })

and if you do not want to check the correct button just delete the return ace[1].checked = true; and in case you wanted to give a alert('Resposta correta') it’s just so :

ace[1].addEventListener('click', function (){
        if(ace != 'N'){alert('Resposta Correta')}

    })

Browser other questions tagged

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