Search code examples
javascriptjqueryjquery-selectors

Get next element with same class in jquery on click


I am trying to create the following.

I have a button and on click of that button i need to add some active class to a div, but i have 4 divs with same class. What am trying to create is like a Choose Bet system like when you click first time on button you choose the first bet, when second time the second, i have 4 bets.

My html structure is the below

<div class="game_paytable_bluebet_column game_paytable_column"></div>
<div class="three_bet_wrappaer">
     <div class="game_paytable_greenbet_column game_paytable_column"></div>
     <div class="game_paytable_orangebet_column game_paytable_column"></div>
     <div class="game_paytable_redbet_column game_paytable_column"></div>
</div>

What i did so far with jquery see below

jQuery('.choose_bet_button').click(function(){
    if(!jQuery('.game_paytable_column:first').hasClass('active_blue_bet')){
        jQuery('.game_paytable_column:first').addClass('active_blue_bet');
    }else{
        jQuery('.game_paytable_column:first').removeClass('active_blue_bet');
        jQuery('.game_paytable_column').next().addClass('active_blue_bet');
    }
});

With this code it is getting 2 elements.

Any idea how to get a solution to this?


Solution

  • Using :eq() you can achieve your requirement. And initialize a counter and based on the counter add class in div. And every four click make the counter 0.

    Please check this snippet.

    var _click = 0;
    $('.choose_bet_button').click(function(){  
      if((_click % $(".game_paytable_column").length)==0){_click=0;}  
    
      $('.game_paytable_column').removeClass('active_blue_bet'); 
      $('.game_paytable_column:eq('+_click+')').addClass('active_blue_bet');
      
      _click++;
      if($.trim($(".in_sight_area").html())==""){
        $(".in_sight_area").html('<div class="top_bet_column_two top_bet_column game_paytable_column">New One</div>');
      }
    });
    .active_blue_bet{
      color:blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     <div class="in_sight_area"></div>
    
    <div class="game_paytable_bluebet_column game_paytable_column">1</div>
    <div class="three_bet_wrappaer">
      <div class="game_paytable_greenbet_column game_paytable_column">2</div>
      <div class="game_paytable_orangebet_column game_paytable_column">3</div>
      <div class="game_paytable_redbet_column game_paytable_column">4</div>
    </div>
    <br/>
    <button class="choose_bet_button">Choose Bet</button>
    
    <div class="game_paytable_redbet_column game_paytable_column">5</div>