I created a simple lottery ticket and I made selector with toggle method. This is my code.
JavaScript
x
4
1
$( "span" ).click(function() {
2
$( this ).toggleClass( "span-selected" );
3
});
4
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:
JavaScript
1
9
1
$( "span" ).click(function() {
2
if (
3
$(this).hasClass("span-selected") ||
4
(!$(this).hasClass(".span-selected") && $(this).closest(".num-cont").find(".span-selected").length < 7)
5
) {
6
$( this ).toggleClass( "span-selected" );
7
}
8
});
9
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.