0

So I have created this table of the 2 products that you may "add to your cart" with their respective quantities. Now, I have it set up to whenever the "add to cart" button is pressed the quantity of that product will be decremented. One thing I am having trouble with is getting the button to disable in respect to when the quantity hits zero. Any help would be appreciated, thanks.

const data = [
{Title: "Beer Heineken 6-pack", Quantity: 5, Price: 6.75, Action: null},
{Title: "Sun-dry Fish 1 lb.", Quantity: 3, Price: 10, Action: null}
];

$(document).ready(function() {
   $("div#preload h2").html();
   let table = $('<table>').addClass('table table-
   striped').appendTo(document.body);
   table.append($('<thead>').append($('<tr>')));
   table.append($('<tbody>'));
   let headerRow = table.find('thead tr');
   Object.keys(data[0]).forEach(function(key) {
    headerRow.append($('<th>').text(key));
})

let tbody = table.find('tbody');

let tableRender = function(){
    data.forEach(function(dataItem, index) {
        let tr = $('<tr>').appendTo(tbody);
        Object.keys(dataItem).forEach(function(key){
            if(dataItem[key] !== null) {
                tr.append($('<td>').text(dataItem[key]));
            }
            else{
                tr.append($('<td>').append($('<button>')
                .addClass('btn btn-secondary').text("Add To Cart")
                .click(function() {
                    dataItem.Quantity = dataItem.Quantity < 1 ? 0 : dataItem.Quantity - 1;
                    tbody.empty();
                    tableRender();



                })));
            }
        })
    })
}

tableRender();
})
Jmpollock56
  • 5
  • 1
  • 4

2 Answers2

0

There's a nice simple jquery example of disabling at this link

It uses the .prop() method to set the "disabled" property of the selected item (your button, in this case) to true.

I'm assuming you already know how to check for your quantity reaching zero :-)

markaaronky
  • 1,231
  • 12
  • 29
0

Since you're redrawing all the table HTML, you'll need to set the button's "disabled" attribute during the redraw, based on whether the quantity is zero or not.

tr.append($('<td>').append($('<button>')
  .prop("disabled", dataItem.Quantity === 0)
  .addClass('btn btn-secondary').text("Add To Cart") //...

(Redrawing the full table HTML may cause you problems down the road, though; any user input or event bindings attached to the table will get blown away when it's redrawn.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53