• Resolved busterland

    (@busterland)


    Hello,

    I’m trying to add JavaScript code for adding a button to Expand/Collapse all rows of my table but I’m not sure I’m doing it in the right way because I get the error :
    DataTables warning: table id=view_2 – Cannot reinitialise DataTable. For more information about this error, please see https://datatables.net/tn/3

    I have added this in my functions.php file in child theme to add javascript code on my website :

    function my_custom_scripts() {
        wp_enqueue_script( 'my-js', get_stylesheet_directory_uri() . '/js/my-js.js', array( 'jquery' ),'',true );
    }
    add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );

    Then in my js file I have added this code to expand / collapse rows :

    jQuery(document).ready(function ($){
        var table = $('#view_2').DataTable({
            'responsive': true
        });
    
        // Handle click on "Expand All" button
        $('#btn-show-all-children').on('click', function(){
            // Expand row details
            table.rows(':not(.parent)').nodes().to$().find('td:first-child').trigger('click');
        });
    
        // Handle click on "Collapse All" button
        $('#btn-hide-all-children').on('click', function(){
            // Collapse row details
            table.rows('.parent').nodes().to$().find('td:first-child').trigger('click');
        });
    });

    And in my page I have added html code :

    <button id="btn-show-all-children" type="button">Expand All</button>
    <button id="btn-hide-all-children" type="button">Collapse All</button>

    The buttons are working but I get the error message. I guess it means that the table is initializing 2 times right ?
    How can I correct this ?

    Thanks ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • Try a test without this. I suspect that is also being done by the WPDA code.

        var table = $('#view_2').DataTable({
            'responsive': true
        });
    
    Thread Starter busterland

    (@busterland)

    Thanks a lot ! It’s working with only :
    var table = $('#view_2').DataTable();

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Adding javascript’ is closed to new replies.