Search code examples
javascriptjqueryarraystoggleclass

Add / Remove specific number of elements from an Array on Click event


I'm trying to make seat booking system that allows a maximum of 4 seats to be selected. Each seat can be selected then deselected on click implementing toggleClass to change status from 'free' 'booked' on seats up to the maxSeats value of 4. It works fine up until the 4th seat is clicked. On a second click to the 4th seat, it does not pop from the tempArray and the class stays as 'booked'. The 1st, 2nd and 3rd seats all add and remove on click I have tried all manner of things to the point where I'm totally devoid of ideas where to go with it. I can see the items being added and removed from tempArray in the console so its not far away.

  // Create an empty array to store the seat ids for click event
    window.tempArray = []; 

    //Handle the click event

    $('#plan').on('click', 'td.n', function() {

        var maxSeats = d.numSeats; //grabbed from JSON

        if ($('.booked').length < maxSeats) { // Use .length to check how many '.booked' DOM elements present

            if ($(this).hasClass('taken')) {
                alert('This Seat Is already booked!');
            } else {
                // Set the class to booked
                $(this).toggleClass('booked');

                // Iterate the .booked elements
                $(this).each(function() {

                    // Getting the id of each seat
                    var seatLocation = $(this).attr('id');

                    // If seatLocation is not inArray - add it - else - pop it off 
                    //$.inArray take (value , name of array)
                    var index = $.inArray(seatLocation, window.tempArray);

                    if (index == -1) { // -1 is returned if value is not found in array
                        window.tempArray.push(seatLocation);

                    } else {
                        window.tempArray.pop(seatLocation);
                    }
                    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'
                    });
                });

Solution

  • Check this fiddle (maxSeats:4 in fiddle).

    // Create an empty array to store the seat ids for click event
    window.tempArray = [];
    
    //A function to update the location div
    function updateLocation(){
        $('#seatLocation').html(window.tempArray.join('-  -')).css({
            backgroundColor: '#F6511D',
            color: '#fff',
            padding: '0.2em',
            borderRadius: '2px',
            margin: '0 10px 0 0'
        });
    }
    
    //Handle the click event
    $('#plan').on('click', 'td.n', function() {
        var maxSeats = d.numSeats; //grabbed from JSON
        var seat=$(this);
        var seatLocation = seat.attr('id');
        if (seat.hasClass('booked')){ // Check if the user changed his mind
                seat.removeClass('booked')
    
                // Delete element in array. 
                // Function from http://stackoverflow.com/a/5767357/1076753
                window.tempArray.splice(window.tempArray.indexOf(seatLocation), 1);
                updateLocation();
                console.log(window.tempArray);
        } 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 {
                seat.addClass('booked')
                window.tempArray.push(seatLocation);
                updateLocation();
                console.log(window.tempArray);
            }
        }
    
    });
    

    PS: think always about the user experience! It's easy, imagine that you are an user and not a developer ;)