Reputation: 465
So I'm very new to web development and am trying to implement a counter that increases when an item is selected, but also decreases if the selected item is unselected. I have the counter increasing when the item is selected but cant seem to get the counter to go down when the item is unselected (it still counts up) the code i have is below(excuse how bad it is like i say I'm new to this)
//highlights current selection and alows a choice of 4 seats to be made
//need to implement unselecting a seat
$('td.n').click(function(){
if(checkcounter())
{
$(this).toggleClass('selected');
$('#seatsAlloc').text(SeatAlloc.toString());
}
});
//cycles through all the seats to check if they are taken or available
//adds taken class to all taken seats
for(x=0;x<=139;x++)
{
if (d.alloc[x] == 1)
{
$($('td.n')[x]).addClass('taken');
}
}
var SeatAlloc = 0;
var Seat_Counter = 0;
function checkcounter()
{
if(Seat_Counter < 4)
{
Seat_Counter++;
SeatAlloc++;
return true;
}
Seat_Counter--;
SeatAlloc--;
return false;
}
If anyone has any help it would be greatly appreciated Thanks!
Upvotes: 1
Views: 73
Reputation: 619
$('td.n').click(function(){
$(this).toggleClass('selected');
$('#seatsAlloc').text($('td.selected').length);
});
This code either removes or adds the class 'selected' to the pressed td and after that it simply counts the amount of td's with the class 'selected'.
Yes it can be that simple.
So if you want max 4 seats selected you can do following.
$('td.n').click(function(){
var amountSelected = $('td.selected').length;
if(amountSelected <= 4) {
$(this).toggleClass('selected');
$('#seatsAlloc').text($('td.selected').length);
}
});
Upvotes: 2