javascript – Dough counter

Question:

The task is to write a test. Questions with three answer options and, depending on the selected answers, respectively, three conclusions.

The counter of answers does not work correctly. The first question gives the correct value, and the following in different ways.

What's my mistake?

I tried to take the result from the current page in this way, it did not help.

var pageN = $ ('.page' + n);
switch ($( 'pageN input[name]:checked' ).val())
var n = 1;
var b = 0,
  m = 0,
  d = 0;

$('#start-test').click(function() {
  $('.page').css("display", "none");
  $('.page1').css("display", "block");
});

$('.arrow-right').click(function() {
  $('.page' + n).css("display", "none");
  onChecked();
  n++;
  $('.page' + n).css("display", "block");

  switch ($("input[name]:checked").val()) {
    case 'B':
      alert('Бизнес');
      b++;
      break;
    case 'D':
      alert('Дизайн');
      d++;
      break;
    case 'M':
      alert('Медиа');
      m++;
      break;
  }

  function onChecked() {
    console.log($("input:radio:checked").val());
  }

  console.log(b, m, d);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<div class="page1">
  <p class="orange-text">Вопрос 1</p>
  <label>
    <input type="radio" value="D" name="answer1">Ответ Д</label>
  <label>
    <input type="radio" value="B" name="answer1">Ответ Б</label>
  <label>
    <input type="radio" value="M" name="answer1">Ответ М</label>
  <img class="arrow-left-off" src="img/arr/back.png" alt="Назад">
  <img class="arrow-right" src="img/arr/next.png" alt="Вперед">
</div>

<div class="page2">
  <p class="orange-text">Вопрос 2</p>
  <label>
    <input type="radio" value="B" name="answer2">Ответ Б</label>
  <label>
    <input type="radio" value="M" name="answer2">Ответ М</label>
  <label>
    <input type="radio" value="D" name="answer2">Ответ Д</label>
  <img class="arrow-left" src="img/arr/back.png" alt="Назад">
  <img class="arrow-right" src="img/arr/next.png" alt="Вперед">
</div>

<div class="page3">
  <p class="orange-text">Вопрос 3</p>
  <label>
    <input type="radio" value="B" name="answer3">Ответ Б</label>
  <label>
    <input type="radio" value="M" name="answer3">Ответ М</label>
  <label>
    <input type="radio" value="D" name="answer3">Ответ Д</label>
  <img class="arrow-left" src="img/arr/back.png" alt="Назад">
  <img class="arrow-right" src="img/arr/next.png" alt="Вперед">
</div>

</html>

Answer:

As @VasilyBarbashev pointed out, although you hide / show different html fragments, the value of $("input[name]:checked").val() always taken from the first "input[name]:checked" on the page.

Limit the selection of inputs to the parent of the button:

switch ($(this).parent().find("input[name]:checked").val()) {

Or your version (corrected):

var pageN = '.page' + n;
switch ($(pageN + ' input[name]:checked').val()) {

but here you need to carefully maintain the current value of n .

Scroll to Top