Liam Liam - 5 months ago 24
jQuery Question

Conditional statement confusion - If 3 show element

I'm trying write a function that allows my user to select 3 elements, once 3 elements are selected a "next" button appears.

My user should then be allowed to deselect one answer and select another, upon deselecting the next button should fade out as there is now only 2 elements selected.

Im struggling to get this working efficiently...

https://jsfiddle.net/p7uhf12L/

$('.answer').on('click',function(e){
e.preventDefault();

if( $('.moreAnswers .selected').length === 3 ){
$('.next-question').fadeIn();
$('.next-question').css('opacity',1);
if($(this).is('.selected')){
$(this).removeClass('selected');
}
} else {
if($(this).is('.selected')){
$(this).removeClass('selected');
$('.next-question').css('opacity',0);
} else {
$(this).addClass('selected');
}
$('.next-question').fadeOut();
$('.next-question').css('opacity',0);
}

if( $('.moreAnswers .selected').length === 3 ){
$('.next-question').fadeIn();
$('.next-question').css('opacity',1);
} else {
$('.next-question').fadeOut();
$('.next-question').css('opacity',0);
}

} );

Answer Source

You can simplify your code like this :

    $('.answer').on('click',function(e){
    e.preventDefault();

    var selected = $('.moreAnswers > .selected').length;

    if(selected == 3){ //if selected is 3 we focus on just deselecting
      if($(this).is('.selected')){ //deselcted and remove links
         $(this).removeClass('selected');
         $('.next-question').fadeOut();
          $('.next-question').css('opacity',0);
      } 
    }else{ //toggle and check if this was the 3rd one
        if($(this).is('.selected')){
            $(this).removeClass('selected');
        } else {
            $(this).addClass('selected');
            if(selected == 2){
             $('.next-question').fadeIn();
           $('.next-question').css('opacity',1);
        }
            }
    }
} );

Sample FIDDLE