JSFiddle - React, Tailwind, and code Playground
by VixedS
HTML
<div id="plan">
<table>
<tr>
<td id="seat1" class="n"></td>
<td id="seat2" class="n taken"></td>
<td id="seat3" class="n"></td>
<td id="seat4" class="n"></td>
<td id="seat5" class="n"></td>
</tr>
<tr>
<td id="seat6" class="n"></td>
<td id="seat7" class="n"></td>
<td id="seat8" class="n taken"></td>
<td id="seat9" class="n"></td>
<td id="seat10" class="n"></td>
</tr>
</table>
</div>
CSS
table{
border-spacing: 10px;
}
.n{background:#09C; width:40px; height:30px;}
.taken{background:#CCC}
.booked{background:#0CF}
JavaScript
// Create an empty array to store the seat ids for click event
window.tempArray = [];
//Handle the click event
function updateSeats(seatLocation,seat){
//$.inArray take (value , name of array)
if ($.inArray(seatLocation, window.tempArray)) { // -1 is returned if value is not found in array
window.tempArray.push(seatLocation);
seat.addClass('booked')
} else {
seat.removeClass('booked');
// Remove the table one time instead of each .booked
window.tempArray.splice(window.tempArray.indexOf(seatLocation), 1);
}
console.log(window.tempArray);
// output added seats to the page...
// join() convert array to a string, putting the argument between each element.
$('#seatLocation').html(window.tempArray.join('- -')).css({
backgroundColor: '#F6511D',
color: '#fff',
padding: '0.2em',
borderRadius: '2px',
margin: '0 10px 0 0'
});
}
$('#plan').on('click', 'td.n', function() {
var maxSeats = 4; //grabbed from JSON
var seat=$(this);
var seatLocation = seat.attr('id');
if (seat.hasClass('booked')){ // Check if the user changed his mind
updateSeats(seatLocation,seat);
} else if ($('.booked').length < maxSeats) { // Use .length to check how many '.booked' DOM elements present
if (seat.hasClass('taken')){
alert('This Seat Is already booked!');
} else {
updateSeats(seatLocation,seat);
}
}
});