Karadjordje Karadjordje - 8 days ago 7
Javascript Question

JQuery click event and toggleClass method

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

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


Now toggle works fine but I want to limit 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

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.
Comments