Search code examples
jqueryarrayssplicearray-splice

Remove item from basket by clicking item element inside the basket


My little project of adding biscuits to a barrel and removing them is nearly complete. I can remove the biscuits by clicking the original button used to add them in the first place. However I'm struggling to remove the biscuit from the barrel by clicking the element of the added biscuit contained within the barrel. So the final result of what I'm trying to achieve is that the user has two ways of removing the biscuit from the barrel.

FIDDLE http://jsfiddle.net/amesy/0hthm28y/

jQuery...

    /*

    Biscuit Slector v1.0

    */


    $(function() { //Add classes to elements

        $('.biscuit').click(function(){
            $(this).toggleClass( "selected"); //Show biscuit as selected
        });

        $('.biscuit.request').click(function(){
            $('.form .request').toggleClass( "show"); //Toggle show and hide special request form when request buscuit is clicked
        });

    });

    var barrel_items = []; //Array of biscuits in barrel
    var barrel = barrel_items; //Set barrel to equal the contents of the array

    $('[data-biscuit]').click(function(){
        var biscuit = $(this).data('biscuit'); // Set Biscuit variable to equal that of biscuit button clicked
        add_to_barrel(biscuit); //Call function that adds biscuit to barrel array
        $("#barrel").val(barrel); //Add biscuit to barrel hidden input
    });


    function add_to_barrel(item){ //Adds biscuit to barrel

        var name = '';
        switch(item){
            case 'custardcream':
                name = 'Custard Creams';
                break;
            case 'jammydodger':
                name = 'Jammy Dodgers';
                break;
            case 'bourbon':
                name = 'Bourbons';
                break;
            case 'nice':
                name = 'Nice';
                break;
            case 'chocolatedigestive':
                name = 'Chocolate Digestives';
                break;
            case 'digestive':
                name = 'Digestives';
                break;
            case 'fruitshortcake':
                name = 'Fruit Shortcakes';
                break;
            case 'gingernut':
                name = 'Gingernuts';
                break;
            case 'oreo':
                name = 'Oreo';
                break;
            case 'hobnob':
                name = 'Hobnobs';
                break;
            case 'cookie':
                name = 'Cookies';
                break;
        }

        // If item is already there in array, it's index will be returned,
        // otherwise indexOf() will return -1
        var indexOfItem = barrel_items.indexOf(item);
        if(indexOfItem !== -1)
        {
            $('.barrel .chosen').eq(indexOfItem).remove();
            barrel_items.splice(indexOfItem,1);
        }
        else
        {
            $('.barrel').append('<div class="chosen">' + name + '</div>');
            //$('.barrel').append("<button type='button' data-biscuit-remove='" + item + "'>"+ name + " Remove</button>");
            barrel_items.push(item);
            //alert(barrel);

        }

        if ( barrel.length ) { // Show barrel if barrel contains items
            $('.form').addClass( "show");
            //$('.empty').removeClass( "show");
            //$( '.empty' ).text( '' );
            //$('.empty').addClass( "hide");
        } else if (!barrel.length) {
            $('.form').removeClass( "show");
            //$( '.empty' ).text( 'Barrel empty' );
            //$('.empty').addClass( "hide");
        }

    }

html...

            <div class="form">

                <form id="f_contact" name="f_contact" method="post" action="thanks.php">

                    <h3>Your barrel contains the following biscuits...</h3>

                    <div class="clearfix"><div class="barrel clearfix"><span class="empty">Barrel empty</span></div></div>

                    <div class="request">

                        <p>Please add your special order of biscuits in the box below...</p>
                        <textarea name="request" cols=40 rows=6></textarea>

                    </div>
                    <input type="hidden" id="name" name="name" value="<? echo $name; ?>" />
                    <input type="hidden" id="barrel" name="barrel" value="" />
                    <input type="submit" id="submit" name="submit" value="Place Order" class="button clearfix" />

                </form>

            </div>

            <ul class="cbp-rfgrid biscuits clearfix">

                <li><button type="button" data-biscuit="custardcream" class="biscuit custardcream" ontouchend="this.onclick=fix">Custard Creams</button></li>
                <li><button type="button" data-biscuit="bourbon" class="biscuit bourbon">Bourbon</button></li>     
                <li><button type="button" data-biscuit="nice" class="biscuit nice">Nice</button></li>   
                <li><button type="button" data-biscuit="jammydodger" class="biscuit jammydodger">Jammy Dodger</button></li> 
                <li><button type="button" data-biscuit="cookie" class="biscuit cookie">Cookie</button></li> 
                <li><button type="button" data-biscuit="chocolatedigestive" class="biscuit chocolatedigestive">Chocolate Digestive</button></li> 
                <li><button type="button" data-biscuit="digestive" class="biscuit digestive">Digestive</button></li> 
                <li><button type="button" data-biscuit="fruitshortcake" class="biscuit fruitshortcake">Fruit Shortcake</button></li> 
                <li><button type="button" data-biscuit="gingernut" class="biscuit gingernut">Gingernut</button></li> 
                <li><button type="button" data-biscuit="oreo" class="biscuit oreo">Oreo</button></li> 
                <li><button type="button" data-biscuit="hobnob" class="biscuit hobnob">Hobnob</button></li> 
                <li><button type="button" data-biscuit="request" class="biscuit request">Request another biscuit?</button></li> 

            </ul>

Solution

  • I would do it like in this JSFiddle where I add a data-biscuitname property on the .chosen div so you can find the biscuit in the barrel_items array, and remove it from the array. Binding the event to clicking on the barrel items is done like so:

    $(".barrel").on("click", ".chosen", function() {
        var biscuitName = $(this).data("biscuitname");
    
        var indexOfItem = barrel_items.indexOf(biscuitName);
        barrel_items.splice(indexOfItem,1);
        $(this).remove();
        $(".biscuits [data-biscuit='" + biscuitName + "']").removeClass("selected");
    });
    

    Note, that when using the .on binding, the event will automatically be attached to all new .chosen elements added to the .barrel element.