Himani
Himani

Reputation: 173

Disable button dynamically in Datatable table column data

I am trying to disable the button present in the last column of Data table. Using the code below works only for the products displayed in the first pagination. If we alter the table length then for the rest of the products, button is enabled.

$.ajax({
    url: custom.ajaxurl,
    type: "GET",
    data: { action: 'checkStoreStatus', store_id: store_id },
    success: function(returned)
    {
    var object = JSON.parse(returned);
    if(object['status'] == 'close'){
        $('.single_add_to_cart_button').prop('disabled', true);

    } else {
        $('.single_add_to_cart_button').prop('disabled', false);
    }
    },
    error: function(exception) {
        console.log("ex:"+exception);
    }
    });

If table length is set to 10 by default then this CSS is applied to only the 10 rows

Table length set to 10

When table length is adjusted to the 25 then the button isn't disabled

enter image description here

Upvotes: 0

Views: 3796

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

DataTable is creating new elements at each draw(). The elements are created from a data object it defined on inititalisation.

So to disable some buttons using its class selector will work only until the next draw, because the data object was not updated. A new set for fresh elements will be created when the user changes the page length... Or filters a column... Etc.

A solution would be to update that data object. It is quite easy to do for a single row. But for the whole table... I would suggest something else.

First, if you do not already, use a variable to store the DataTables instance:

var table = $('#example').DataTable();

Then, use a global scope variable for the store open/closed state:

var storeClosed = false; // Default state, buttons enabled

And use the DataTables draw event to enable/disable the buttons:

table.on('draw', function(){
  $('.single_add_to_cart_button').prop('disabled', storeClosed);
});

In the Ajax request, just update the variable:

$.ajax({
  url: custom.ajaxurl,
  type: "GET",
  data: { action: 'checkStoreStatus', store_id: store_id },
  success: function(returned){
    var object = JSON.parse(returned);
    if(object['status'] == 'close'){
      storeClosed = true;

    }else{
      storeClosed = false;
    }
    // Apply the change
    $('.single_add_to_cart_button').prop('disabled', storeClosed);
  },
  error: function(exception){
    console.log("ex:"+exception);
  }
});

Upvotes: 1

Related Questions