How do I add a table cell that has a shopping cart "Add to Cart" button with a quantity field?

How do I add a table cell that has a shopping cart "Add to Cart" button with a quantity field?

webpointzwebpointz Posts: 126Questions: 30Answers: 4

I'm using the latest datatables package and I want to show a table of products with pagination and beside each product (row) I want to put an "add to cart" button that when depressed after adjusting quantity, will be disabled.

I have no idea where to start but I have a regular table that does it at the moment using javascript that updates a session array.

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Use the columns.render or columns.defaultContent option to return the HTML you want for the button. Also set columns.data to null for that column since it doesn't need any data from the source.

    There is an Editor example of that available here (ignore the Editor aspect, and focus just on how the links are added to the table).

    Allan

  • webpointzwebpointz Posts: 126Questions: 30Answers: 4

    Thanks Allan

  • webpointzwebpointz Posts: 126Questions: 30Answers: 4

    Hi Allan

    I can't seem to get things to work. Basically I want a far right column that has an <input type="number"> with a <button> that when the user clicks on the button, it will perform an ajax post of the productid and quantity to a PHP session array (shopping cart).

    I have tried a bunch of things using "render" to no avail and this is the last piece I need to complete for my application.

  • webpointzwebpointz Posts: 126Questions: 30Answers: 4

    Basically, I have a table with ONE column coming from the database (product-id) and I wish to add TWO extra columns...ONE column that has an INPUT TYPE="number" and ONE column that has the <BUTTON>.

  • webpointzwebpointz Posts: 126Questions: 30Answers: 4

    Update:

    Hi Allan, I managed to get most of it working however, I'm wondering if you can guide me on a final part?

    Here is the code I have:

        $.extend( $.fn.DataTable.defaults, {
                responsive: true
            } );        
            
            $(document).ready(function() {
                
            
                $('#example').on( 'click', 'button', function() { 
                    var data1 = table.row( $(this).parents('tr') ).data();
                    var data2 = $(this).closest('td').prev().find('input').val();
                    alert( data1 + ", " + data2 );
                } );    
            
                var table = $('#example').DataTable( {
                    "iDisplayLength": 5,
                    "aLengthMenu": [[5, 10, 15, -1], [5, 10, 15, "All"]],
                    "language": { "infoFiltered": ""},          
                    "order": [[ 1, "desc" ]],
                    "processing": true,
                    "serverSide": true,
                    "ajax": "scripts/server_processing2.php",
    
                    "columnDefs": [ {
                            "targets": -2,
                            "data": null,
                            "defaultContent": '<input type="number" name="quantity" value="1" min="1" style="width:100%;" class="form-control" placeholder="Type quantity here...">'
                            },
                            {
                            "targets": -1,
                            "data": null,
                            "defaultContent": '<button type="submit" class="btn btn-primary add-to-cart"><span class="glyphicon glyphicon-shopping-cart"></span> Add</button></span>'                       
                            }
    
                            ]
                            
                } );
            } );
    

    I can now get the quantity for the row in question (I'm currently throwing it into an alert message), but once I process the entry to the SESSION array using AJAX, I want to be able to have a user move around the datatable (pagination) with the chosen QUANTITY locked for the row they just added if they go back AND I want to change the "defaultContent" for both custom columns so that on the rows submitted, the INPUT and BUTTON class names are changed and disabled.

    Any thoughts?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    I want to change the "defaultContent" for both custom columns so that on the rows submitted, the INPUT and BUTTON class names are changed and disabled.

    Unfortunately there is no way to change the default content after initialisation. You would need to use a draw callback event to modify the elements that the default content has put into the document.

    , I want to be able to have a user move around the datatable (pagination) with the chosen QUANTITY locked for the row they just added if they go back

    The problem you'll face there is that you are using server-side processing, so the row (as far as the client-side is concerned) only exists for as long as it is shown. You would need to submit it to the server so it can then be redisplayed in future.

    Allan

  • webpointzwebpointz Posts: 126Questions: 30Answers: 4

    Thanks Allan,

    I used the following and it works FANTASTIC! :

    ``` $(document).ready(function() {

                // Order by the grouping
                $('#example').on( 'click', 'tr.group', function () {
                    var currentOrder = table.order()[0];
                    if ( currentOrder[0] === 2 && currentOrder[1] === 'asc' ) {
                        table.order( [ 2, 'desc' ] ).draw();
                    }
                    else {
                        table.order( [ 2, 'asc' ] ).draw();
                    }
                } );    
    
    
            $('#example').on( 'click', 'button', function() { 
                var thisCartItem = $(this);
                var data1 = table.row( $(this).parents('tr') ).data();
                var data2 = $(this).closest('td').prev().find('input').val();
                var thisCartQTY = $(this).closest('td').prev().find('input');
                var dataString = data1 + ',' + data2;
                var jsonString = JSON.stringify( dataString );
    
    
                   $.ajax({
                        type: "POST",
                        url: "add_to_cart2.php",
                        data: {data : jsonString}, 
                        dataType: "JSON",
                        cache: false,
    
                        success: function(response){
                            //alert(data1[1]+' has been added to the cart');
                            $('#shoppingcartcount').text(response.shopcount);
                            $(thisCartItem).html( "<span class='glyphicon glyphicon-shopping-cart'></span> Item Added" );
                            $(thisCartItem).toggleClass('btn-primary btn-success');
                            $(thisCartItem).prop('disabled', true); 
                            $(thisCartQTY).prop('disabled', true); 
                        }
    
                    });             
    
            } );    
    
            var table = $('#example').DataTable( {
    
                "fnInitComplete": function(oSettings, json) {
    
                <?php 
    
                if(count($_SESSION['cart'])>0){
    
                    foreach($_SESSION['cart'] as $id=>$value){
                        //echo "alert('" . $id . "|" . $_SESSION['cart'][$id]['quantity'] . "');";
                        echo "$('#qty_" . $id . "').val('" . $_SESSION['cart'][$id]['quantity'] . "');"; 
                        echo "$('#btn_" . $id . "').html(\"<span class='glyphicon glyphicon-shopping-cart'></span> Item Added\" );";
                        echo "$('#btn_" . $id . "').toggleClass('btn-primary btn-success');";
                        echo "$('#qty_" . $id . "').prop('disabled', true);";
                        echo "$('#btn_" . $id . "').prop('disabled', true);";
                    }               
                }
    
                ?>
    
                    },          
                    "scrollY": "380px",
                    "scrollCollapse": true,
                "iDisplayLength": -1,
                "paging": false,
                "bFilter": false,
                "language": { "infoFiltered": ""},          
                "processing": true,
                "serverSide": true,
                "ajax": "scripts/server_processing2.php",
                 "columnDefs": [ 
                { "visible": false, "targets": 0 },
                { "visible": false, "targets": 2 },
                { "targets": -2,
                    "data": "quantity",
                                "render": function ( data, type, full, meta ) {
                     return '<input id="qty_'+full[0]+'" type="number" name="quantity" value="1" min="1" style="width:100%;" class="form-control" placeholder="Type quantity here...">';
                    }},
                { "targets": -1,
                    "data": "action",
                                "render": function ( data, type, full, meta ) {
                     return '<button id="btn_'+full[0]+'" type="submit" class="btn btn-primary add-to-cart"><span class="glyphicon glyphicon-shopping-cart"></span> Add</button></span>';
                    }}                  
                ],
                "order": [[ 2, 'asc' ]],
                    "drawCallback": function ( settings ) {
                        var api = this.api();
                        var rows = api.rows( {page:'current'} ).nodes();
                        var last=null;
    
                        api.column(2, {page:'current'} ).data().each( function ( group, i ) {
                            if ( last !== group ) {
                                $(rows).eq( i ).before(
                                    '<tr class="group"><td colspan="4"><strong>'+group+'</strong></td></tr>'
                                );
    
                                last = group;
                            }
                        } );
                    }               
    
            } );
    
        } );
    

    ```

This discussion has been closed.