class

class

k-georgek-george Posts: 26Questions: 3Answers: 0
edited November 22 in Free community support

https://live.datatables.net/vohiyelo/3/edit

Error as seen in the test case:

Trying to add two classes to all odd rows.

How to add two classes to all odd rows that needs to work with both client side and server side process?

«1

Answers

  • allanallan Posts: 65,409Questions: 1Answers: 10,859 Site admin
        drawCallback: function () {
          $('#example tbody tr').removeClass('odd');
          $('#example tbody tr:odd').addClass('odd')
        }
    

    That will remove the odd class from any existing rows in the body (for cases when a row was odd, but has been moved to become even!), and then adds it on.

    However, if it is just for styling, then just use CSS:

    #example tbody tr:nth-child(odd) {
      ...
    }
    

    Allan

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Thanks for the reply.

    Two more matters to get clarity.

    1- Difference between (in simple words)

    a) "rowCallback": function ()

    b) "drawCallback": function ()

    2 How to add it rowCallback / drawCallback function on a button click ?

    george.

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    The option rowCallback and drawCallback docs explain it best.

    a) "rowCallback": function ()

    This callback allows you to 'post process' each row after it have been generated for each table draw, but before it is rendered into the document.

    b) "drawCallback": function ()

    Function that is called every time DataTables performs a draw.

    You can use a console.log() statement in each callback to see the behavior and when the run.

    How to add it rowCallback / drawCallback function on a button click ?

    Call draw() to execute the option rowCallback and drawCallback functions.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Thanks for the reply.

    Actually don't know the logic required to add the below with a button click

    "drawCallback": function () {
    $('#example tbody tr').removeClass('odd');
    $('#example tbody tr:odd').addClass('odd')
    }

    can you show me onetime ?

    george

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    Like this:
    https://live.datatables.net/vohiyelo/7/edit

    Not sure having a button for just redrawing the table to execute that particular code in drawCallback is very useful. drawCallback will run anytime the table is drawn for example anytime the table is sorted, searched or changing the page.

    What are you trying to do with the button?

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    What are you trying to do with the button?

    Answer - only call or function the 'drawCallback' on that button click.

    I don't know that 'how to do that.

    george

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137
    edited November 22

    As I said to execute the drawCallback function call the draw() API. This is what my example shows:
    https://live.datatables.net/vohiyelo/7/edit

    However maybe you just want to execute an independent function when clicking a button. Something like this:
    https://live.datatables.net/vohiyelo/9/edit

      $('#update-class').on('click', function () {
          $('#example tbody tr').removeClass('odd');
          $('#example tbody tr:odd').addClass('my-odd')
      });
    

    Sorry, I'm still not clear on what exactly your requirement is.

    Kevin

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    Maybe this example of calling the drawCallback function using a button click will be more clear:
    https://live.datatables.net/vohiyelo/14/edit

    If you still have questions then please provide details of what you want to do within the function when the button is clicked. Understanding your requirements will allow us to provide better suggestions.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

      Thanks for the answer.
    

    Your question '..........what you want to do.........' ?

        We just trying to learn datables and while thinking or discuss within us or while learning new thinking just happen.
    

    For example the drawCallback function.

    So normally we can use it as

    drawCallback: function () {
        $('#example tbody tr').removeClass('odd');
        $('#example tbody tr:even').addClass('red-odd');
    
    }
    

    but new thing was 'how to do that on a button click'

    So many ways on few days we play with our own knowledge and findings.

    And when we think that unable to solve us that time we make a post.

    Now few days we playing on with how to do with odd and even columns for the same drawCallback function.

    $('#example tbody td:even').addClass('even-column');

    we try with these

    td:nth-child(even)

    td:even

    tbody td:nth-child(even)

    tr td:nth-child(even)

    etc.

    Hope you understand us ?

    How to do it with odd and even column for the same drawCallback function ?

    george & friends.

  • allanallan Posts: 65,409Questions: 1Answers: 10,859 Site admin

    but new thing was 'how to do that on a button click'

    Set a variable when the button is clicked and check for that variable in the draw callback, which is exactly what Kevin showed in his latest example. Perhaps you want it to toggle? Updated example here.

    Allan

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

        With add to rows using drawCallback function methods are get cleared by you.
    

    The last question was how to use with odd and even column to add a class with using drawCallback function method

    The test case at https://live.datatables.net/vohiyelo/20/edit

    As mentioned in the previous query / reply we express some of the methods we used ?

    Or whether it is impossible to add a calss to all even and odd column using drawCallback function ?

    If it is not possible then what's the next best method ?

    george and friends.

  • allanallan Posts: 65,409Questions: 1Answers: 10,859 Site admin

    Your CSS was:

    tr.red-odd {
      color: red;
    }
    

    But you are applying the class to td elements. Use:

    tr.red-odd,
    td.red-odd {
      color: red;
    }
    

    Allan

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    There are no restrictions to using `-option drawCallback. It is a standard Javascript function. However it only executes when the Datatable is redrawn.

    Right click and inspect on of the rows. You can see the red-odd class is added to the odd columns:

    You don't have a CSS defined to apply any styling for a td with that class. For example:
    https://live.datatables.net/redizuxu/1/edit

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

      If using 
    

    td.red-odd {
    color: violet;
    }

    and

    drawCallback: function () {

     $('#example tbody tr').removeClass('red-odd');
    
    
        $('#example tbody tr td:nth-child(odd)').addClass('red-odd');
    
      }
    

    https://live.datatables.net/redizuxu/2/edit

    everything works fine until we hide a column.

    If we hide a column then the odd column class is not changing.

    then clicking for the next page everything goes scramble.

    george and friends

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    Use the column-visibility event to call draw() when the visibility changes. Also you will want to remove the red-odd class from all tds in drawCallback. Updated example:
    https://live.datatables.net/redizuxu/4/edit

    Kevin

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    Just to add to my last comment. Many Datatables actions that affect the columns displayed, like responsive or colReorder, have events that fire so you can perform an action when these events occur.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

    Test case at https://live.datatables.net/tuxohazo/2/edit

    What we trying to achieve is 'add a class to that hyperlink if clicked'.

    But at the test case if click a link in any page other than the first page the class appear to all links in the first page only.

    we trying to add the class only the clicked link.

    not yet success.

    george and friends

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137
    edited December 2

    we trying to add the class only the clicked link.

    This isn't a Datatables issue. First start by clicking on the Live preview button. The button is the upward/right facing arrow in the top right corner of the Output tab. Now you can see the behavior of your page.

    When clicking a link only that link has the class toggled. The other link on the page is unaffected.

    However if you reload the page then all the links on that page have the class added. Its due to this code:

        clickedLinks.forEach(function(href) {
            $('a[href="' + href + '"]').addClass('clicked-link');
        });
    

    You have the same URL for each link so this is applying the restored localStorage to all the https://www.w3schools.com/ inks on the page. If the page ha unique links then the code should work. If they aren't unique then you will need to save something like the row ID (row().id()) or row index (row().index()) or some other unique item from each row.

    Kevin

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137
    edited December 2

    There is one change you will need to make. Once Datatables initializes then only those rows on the current page are in the document. Use rows().nodes() as part of the jQuery selector to find all the rows:

        clickedLinks.forEach(function(href) {
            $('a[href="' + href + '"]', table.rows().nodes()).addClass('clicked-link');
        });
    

    https://live.datatables.net/tuxohazo/3/edit

    Note that I changed the URLs to be unique.

    Kevin

  • allanallan Posts: 65,409Questions: 1Answers: 10,859 Site admin

    What we trying to achieve is 'add a class to that hyperlink if clicked'.

    Use the :visited pseudo class.

    As Kevin says, this isn't a DataTables issue. General CSS / JS questions are bast directed to StackOverflow.

    Allan

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

    Kevin - one more thing is there that how to focus on each cell rather than unique id to the link ?

    may be same link is applicable for different matters ?

    Allan - why we contacted datatables.net is you are the creators. So you know things better than anyone ?

    We like to express our words as like you that data contains anything and the requirements may differ as well ?

    So we believe every data and requirements get noticed for improvements to get versatile solutions ?

    note : same like heath and safety methods / procedures that every incidents and accidents may reported ?

    george and friends.

  • allanallan Posts: 65,409Questions: 1Answers: 10,859 Site admin

    My point was that for general Javascript and CSS questions, you should ask on StackOverflow or similar. For DataTables specific questions, yes, of course ask here.

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137
    edited December 2

    is there that how to focus on each cell rather than unique id to the link ?

    Without knowing your data structure it's hard to say specifically. I would set a unique ID for each row. If you are using ajax or data loaded data then use the rowId to tell Datatables the row property to use as the ID.

    In the click event use row().id() to get the ID and store that in the loacalStorage array. Use cell().node() to fetch the appropriate column when restoring the links, for example:

        clickedLinks.forEach(function( id ) {
            $( table.cell( '#' + id, 0 ).node() ).find('a').addClass('clicked-link');
        });
    

    Updated test case:
    https://live.datatables.net/lekavaku/1/edit

    I added the id attribute to each row and reverted the URLs to the same link.

    You may need to clear the localStore to remove the stored URL's.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

      We add the id to each row like this
    

    DataTable('#example', {

    "createdRow": function(row, data, dataIndex) {
    // Assign a sequential ID starting from 1
    $(row).attr('id', 'row-' + (dataIndex + 1));
    }

    });
    

    Whether the above is the correct method ?

    and updated case at https://live.datatables.net/tuxohazo/5/edit

    but the class is not adding once clicked the link.

    george and friends.

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137
    edited December 3

    First your test case isn't running as you expect. This error is showing in the browser's console:

    Uncaught TypeError: Cannot set properties of undefined (setting '$')

    You have this:

        var table = $('#example').DataTable(); // Initialize your DataTable
    
      
      DataTable('#example', {
    
      createdRow: function(row, data, dataIndex) {
                // Assign a sequential ID starting from 1
                $(row).attr('id', 'row-' + (dataIndex + 1)); 
            }
        
        });
    

    The Datatable is initialized in line 1. Line 4 is generating an error due to incorrect syntax. See the docs for the two ways Datatables is initialized.

    First remove line 1 so you don't get the Warning: Cannot reinitialise DataTable error. Next add new to line 4 like this:

    var table = new DataTable('#example', {
    

    Using createdRow to add the row ID's is too late for Datatable to read the IDs, during initialization, for use with the row().id() API. Datatables reads each row of an HTML sourced table and will keep track of the assigned ID of eachtr in it's data cache. createdRow happens after this initial loading of the HTML table.

    Instead use jQuery to get the ID attribute in the click event, for example:

            // Get row ID
            var row = $(this).closest('tr');
            // var rowID = table.row( row ).id();
            // Use jquery to get the row ID
            var rowID = $(row).attr('id');
    

    https://live.datatables.net/tuxohazo/7/edit

    Using createdRow may not work reliably. If the HTML table rows change order or quantity on reload then the IDs won't be the same. It's best to have the IDs as part of the original data source so they are always the same.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

        1- Suppose use the below method to initialize the table.
    

    $(document).ready(function() {
    var table = $('#example').DataTable(); // Initialize your DataTable
    });

    Whether possible to add other functions like createdRow / drawCallback / etc. etc. as a standalone method without changing the above initialization method ?

    2- How to find all available functions like createdRow / drawCallback / etc. etc. from your website ?

    3- What are the best methods to add other functions to both client and server side processing after initializing with the above method ?

    george

  • kthorngrenkthorngren Posts: 22,357Questions: 26Answers: 5,137

    Whether possible to add other functions like createdRow / drawCallback / etc. etc. as a standalone method without changing the above initialization method ?

    The Initializing Datatables docs docs state this:

    If you want to customise your DataTable, this can be done by specifying configuration parameters in an object passed to the DataTable() function. For information on how to use these configuration parameter, please refer to the options manual page.

    Essentially if you want to use non-default settings then add them into the initialization object.

    How to find all available functions like createdRow / drawCallback / etc. etc. from your website ?

    These can be found by clicking the Reference link found on the left side menu of this page. The Options link contains all the docs for the initialization options.

    What are the best methods to add other functions to both client and server side processing after initializing with the above method ?

    Datatables doesn't support adding options after initialization. You would need to reinitialize Datatables with the new set of options. To reinitialize you will need to destroy the current Datatable.

    Kevin

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

           Have toggle column visibility button for some columns.
    

    For example column 1.

    How to use / express each state visibility to do something ?

    How to make the length menu to any other number (for example 25 rows per page and total selections have 10, 20, 25. 50 etc.) rather than the first one as default setting ?

    Rebecca / George & friends.

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

        Using this initialization method / settings at
    

    https://live.datatables.net/tuxohazo/7/edit

    How to add

    table.on('draw', function() {}

    and

    table.on('draw', function() {}

    Hanna / George & friends.

  • k-georgek-george Posts: 26Questions: 3Answers: 0

    Hi,

          One correction is there on the second function mentioned on the previous message (written as table.on('draw', function() {}).
    

    But read it as

    drawCallback: function(settings) {}

    Hanna / George & friends.

Sign In or Register to comment.