0

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

1 Answer 1

1

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);
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton, solution you provided works like a charm :)
Only for he initial table draw, I need to apply the css in ajax funtion too. Edited your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.