Skip to content
Advertisement

JQuery click event and toggleClass method

I created a simple lottery ticket and I made selector with toggle method. This is my code.

  $( "span" ).click(function() {
  $( this ).toggleClass( "span-selected" );
});

The toggle functionality works fine but I want to add a limitation so that only 7 numbers can be chosen in one container. Is there a way to achieve this. Here is my JSBIN > http://jsbin.com/menawu/1/edit?js,output

Advertisement

Answer

You need to check if there are already 7 elements checked in that container, like so:

$( "span" ).click(function() {
  if (
     $(this).hasClass("span-selected") || 
     (!$(this).hasClass(".span-selected") && $(this).closest(".num-cont").find(".span-selected").length < 7)
  ) {
       $( this ).toggleClass( "span-selected" );
   }
});

So your criteria are:

  • if it’s not selected, check if there are less than 7: if yes, toggle, otherwise don’t do anything
  • if it is selected, unselect it.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement