jQuery addClass example

Change class name on click in jQuery

by khamer

HTML

<div class="question active">
  <p>Lorem ipsum dolor sit amet.</p>
  <input type="radio" name="thing1" value="foo">
  <input type="radio" name="thing1" value="bar">
  <button>next</button>
</div>
<div class="question">
  <p>Quasi facilis, voluptatem delectus ea.</p>
  <input type="radio" name="thing2" value="foo">
  <input type="radio" name="thing2" value="bar">
  <button>next</button>
</div>
<div class="question">
  <p>Labore optio et reiciendis debitis.</p>
  <input type="radio" name="thing3" value="foo">
  <input type="radio" name="thing3" value="bar">
  <button>next</button>
</div>
<div class="question">
  <p>Consequuntur deleniti, alias dolorum eveniet!</p>
  <input type="radio" name="thing4" value="foo">
  <input type="radio" name="thing4" value="bar">
  <button>next</button>
</div>

SCSS

.question {
  display: none;
}

.question.active {
  display: block;
}

JavaScript

$(function() {
	var questions = {};
  
  var $allQuestions = $('.question');
  
  $('.question button').click(function() {
  	var selectedRadio = $(this).parents('.question')
    	.find('input[type=radio]:checked');
    
    if (selectedRadio.length == 0) {
    	return;
    }
    
    questions[ selectedRadio.attr('name') ] = selectedRadio.val();
    
    $allQuestions.filter('.active')
    	.removeClass('active')
      .next()
      .addClass('active');
    
    console.table(questions);
    
    if ($(this).attr('name') == 'thing4') {
    	// all four answered
      
      if (questions.thing1 == 'foo' && questions.thing2 == 'bar') {
      	alert('you did it');
      } else {
      	alert('you goofed');
      }
    }
  });
})