Suggestion: Dynamic changing of table headers

Suggestion: Dynamic changing of table headers

Khalid TeliKhalid Teli Posts: 251Questions: 71Answers: 0

Hi,
I really need some advice regarding the best way to deal with dynamic table headers.

I have datatable, on the each value selection using dropdown menu, the table redraws and the header name changes

at the moment, I am doing it by hardcoding , like the example below

if(target == "Tomatoes"){
        $( table.column(0).header() ).html('2 Boxes');
   $( table.column(1).header() ).html('3 Boxes');
   $( table.column(2).header() ).html('4 Boxes');

if(target == "Milk"){
        $( table.column(0).header() ).html('2 Ltrs');
   $( table.column(1).header() ).html('5 ltres');
   $( table.column(2).header() ).html('6 ltrs');
 and it continues..........

The issue is that, I have at least 150 products and defining the column header name for each product separately is going to make code longer/messy and time consuming. In addition to this, I need to amend column header names sometimes.

Can anyone please suggest me what is the best way to deal with this situation.

can I save them in json file/database and then append them to table?

Thank you
Kind Regards,
KT

Answers

  • kthorngrenkthorngren Posts: 21,174Questions: 26Answers: 4,923

    I would look at using a Javascript object, something like this:

    var products = {
        Tomatoes: {0: '2 Boxes', 1: '3 boxes', 2: '4 Boxes'},
        Milk: {0: '2 Ltrs', 1: '5 Ltrs', 2: '6 Ltrs'},
    }
    

    Then do something like this:

       var product = products[target];
       $( table.column(0).header() ).html(product[0]);
       $( table.column(1).header() ).html(product[1]);
       $( table.column(2).header() ).html(product[2]);
    

    You could turn this into a for loop.

    How you build the products object is up to your specific environment, Could be done client or server side.

    Kevin

  • Khalid TeliKhalid Teli Posts: 251Questions: 71Answers: 0

    @kthorngren
    Thank you very much!!!!
    Created the js object on clients side and is working perfect. This will definitely save me loads of time.

    Implement on the server side as well and again works perfect

    $.ajax({
            type:'POST',
           url:"xxx/xxx/headers_fetch.php",
           success: function (data) {
             data = JSON.parse(data);
             var target = $('#col3_filter option:selected').val();
    
    var header = data.data.filter((x) => { return x.contract_prod == target; });
    //console.log(header);
    
     $( table.column(0).header() ).html(header[0].opt_one);
     $( table.column(1).header() ).html(header[0].opt_two);
     $( table.column(2).header() ).html(header[0].opt_three);
      }
        });
    

    Thank you

This discussion has been closed.