Ganesh Yadav
Ganesh Yadav

Reputation: 2685

JS variable increment onclick

I have multiple boxes with a button. I want onclick select button variable increment. I don't want to be selected more than 6 so I have disabled other buttons.

Fiddle Demo Here

If I remove any element. The removed one should continue on next click. Please see demo for better understanding.

var ct = ["1","2","3","4","5","6"];
var i = -1;

$('.goal1').each(function(index){
  $(this).on('click', function(e){
    i = i+1;
    i = i % ct.length;

    $(this).parents('li').addClass('selected');
    $(this).fadeOut('50', function(){
      $(this).parents('li').find('.goal2').fadeIn('50');
    });
    $(this).parents('li').find('.counter').text(ct[i]);
    if($('li.selected').length >  5){
            $('.goal1').prop('disabled', true);
    }
    e.preventDefault();
  });
});

$('.goal2').each(function(index){
      $(this).on('click', function(e){
        i = i-1;
        i = i % ct.length;
        $(this).parents('li').removeClass('selected');
        $(this).fadeOut('50',function(){
          $(this).parents('li').find('.goal1').fadeIn('50');
        });
        $(this).parents('li').find('.counter').text('');
                $('.goal1').prop('disabled', false);
        e.preventDefault();
      });
});

Upvotes: 0

Views: 259

Answers (1)

Jayesh Patel
Jayesh Patel

Reputation: 289

Try below code it might help you:

var ct = ["1","2","3","4","5","6"];
var i = -1;
var j = [];

$('.goal1').each(function(index){
      $(this).on('click', function(e){
        i = i+1;
        i = i % ct.length;

        $(this).parents('li').addClass('selected');
        $(this).fadeOut('50', function(){
          $(this).parents('li').find('.goal2').fadeIn('50');
        });
        if(j.length > 0){
            $(this).parents('li').find('.counter').text(j.pop());
        }
        else
            $(this).parents('li').find('.counter').text(ct[i]);
        if($('li.selected').length >  5){
                $('.goal1').prop('disabled', true);
        }
        e.preventDefault();
      });
});

$('.goal2').each(function(index){
      $(this).on('click', function(e){
        i = i-1;
        i = i % ct.length;
        $(this).parents('li').removeClass('selected');
        $(this).fadeOut('50',function(){
          $(this).parents('li').find('.goal1').fadeIn('50');
        });
        j.push($(this).parents('li').find('.counter').text());
        $(this).parents('li').find('.counter').text('');
                $('.goal1').prop('disabled', false);
        if($('li.selected').length ==  0){
                j = [];
        }
        e.preventDefault();
      });
});

You can change var j behavior as per your need.

Upvotes: 1

Related Questions