Click function to toggle column visibility is performed once on first click, twice on second, etc

Click function to toggle column visibility is performed once on first click, twice on second, etc

GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

Each time I click on the "#archivedHidden" button the number of times the function to toggle column visibility is triggered is increased by one.

$(document).ready(function(){

    $("#includedContent").load("Menu.html");

    $('[data-toggle="tooltip"]').tooltip();

    $('#ajaxGetUserServletResponse').text('');
    $('#ajaxGetUserServletResponse2').text('');

    $("#showAccountUpdateForm").hide();
    sessionStorage.setItem('ssArchived', "Hidden");
//  alert(sessionStorage.getItem('ssArchived'));

    $("#datepicker1").datepicker({
      showOn: "both",
      format: 'dd/mm/yyyy',
    });

    jQuery.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "Please enter correct Characters."
    );


    //Display the Accounts
    $('#archivedHidden').click(function(){      

        if($(this).text().trim() == 'Archived Hidden' ){
            $(this).text('Archived Shown');
            sessionStorage.setItem('ssArchived', "Shown");
//          alert(sessionStorage.getItem('ssArchived'));

            showDataTable();

        }else{
             $(this).text('Archived Hidden');
             sessionStorage.setItem('ssArchived', "Hidden");
//           alert(sessionStorage.getItem('ssArchived'));

             showDataTable();
        }
    });

    showDataTable();

    //Validate form showAccountUpdateForm
    $("#showAccountUpdateForm").validate({
        //debug: true,

        rules: {
            password: {
                required: true,
                regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/,
                minlength: 8
            },
        },

        messages: {
            enterPassword1: {
                regex: "Please enter at least 8 characters containing at least 1 lower case, 1 upercase, 1 special and 1 numeric.",
                minlength: "Your password must consist of at least 8 characters.",
            },
        },

        submitHandler : function(showAccountUpdateForm) {
            //do something here
            //var frm = $('#contactForm');
            //alert($("#accountName").val());

            $.ajax({
                url : 'AccountUpdateView', // Your Servlet mapping or JSP(not suggested)
                data : {
                    ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
                    ssResAccountID : sessionStorage.getItem('ssResAccountID'),
                    password : $("#password").val(),    
                },  
                type : 'POST',
                dataType : 'html' // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.  
            })
            .fail (function(jqXHR, textStatus, errorThrown) {
                //alert(jqXHR.responseText);
                $('#ajaxGetUserServletResponse').text('Error updating Account.');
            })
            .done(function(responseJson){
                $('#ajaxGetUserServletResponse').text('Account updated.');
            })
        }
    }); 
}); // end document.ready

function showDataTable() {
    //Show DataTable
    if ( $.fn.dataTable.isDataTable( '#accountUpdateTable' ) ) {
        var accountUpdateTable = $('#accountUpdateTable').DataTable();

      //Toggle the "Archived" column
        $('#archivedHidden').on( 'click', function (e) {
            alert("Toggle column");
            e.preventDefault();

            // Get the column API object
            var column = accountUpdateTable.column(6);

            // Toggle the visibility
            column.visible( ! column.visible() );
        } );
    }
    else {
        var accountUpdateTable = $('#accountUpdateTable').DataTable( {

            "info":     false,
            dom: 'Bfrtip',
            buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
            columns: [
                  {data: 'accountId',
                      visible: false,
                      searchable: false},
                  {data: 'emailaddress'},
                  {data: 'surname',
                      defaultContent: ""},
                  {data: 'otherNames',
                      defaultContent: ""},
                  {data: 'level',
                      defaultContent: ""},
                  {data: 'enabled',
                      defaultContent: ""},
                  {data: 'archived',
                      visible: false,
                      defaultContent: ""},
                  {data: null,
                      className: "center",
                      defaultContent: '<button id="reset">Reset</button>'
                  }
                 ],
             columnDefs: [ {
                 targets: [6],
                 render: $.fn.dataTable.render.moment( 'DD/MM/YYYY' )
             } ],
        } );

        //Toggle the "Archived" column
        $('#archivedHidden').on( 'click', function (e) {
            alert("Toggle column");
            e.preventDefault();

            // Get the column API object
            var column = accountUpdateTable.column(6);

            // Toggle the visibility
            column.visible( ! column.visible() );
        } );
    }


    //Get Account List
    $.ajax({
        url : 'AccountsListView', // Your Servlet mapping or JSP(not suggested)
        data : {
            ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
            ssAccountID : sessionStorage.getItem('ssAccountID'),
            ssArchived : sessionStorage.getItem('ssArchived'),
        }, 
        type : 'POST',
    })
    .fail (function(jqXHR, textStatus, errorThrown) {
//      alert(jqXHR.responseText);
        if(jqXHR.responseText.includes('No Accounts')){
            $('#ajaxGetUserServletResponse3').text('No Accounts.');
        }else{
            $('#ajaxGetUserServletResponse3').text('Error getting Accounts.');
        }
        accountUpdateTable.clear().draw();
    })
    .done(function(responseJson1a){
        // JSON response to populate the activities table
        dataType: "json";

//      alert(JSON.stringify(responseJson1a));
//      Result of alert is:
//          [{"adId":"2","grpId":"2","adActivityID":"2","adActivityName":"Visit Ryde Fire Station","adStartDate":"2017-05-24","adEndDate":"2017-05-24"}]
        accountUpdateTable.clear();
        accountUpdateTable.rows.add(responseJson1a).draw();
    })

    $('#accountUpdateTable tbody').on( 'click', '#reset', function () {
//      alert("Reset");
        var data = accountUpdateTable.row( $(this).parents('tr') ).data();

        sessionStorage.setItem('ssResAccountID', data.accountId);
        $("#account").val(data.emailaddress);
        $("#password").val("");

        $("#showAccountUpdateForm").show();

    } );
}

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    Hi @Glyndwr ,

    It's because within the function showDataTable() you're creating a new event listener on each iteration

    $('#archivedHidden').on( 'click', function (e) {
    

    Either disable previous ones with off() or refactor the code so you don't need to keep create additional listeners.

    Cheers,

    Colin

  • GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

    Yes you are right. I have cleaned it up and placed after the if{}else{}

    //Toggle the "Archived" column
    $('#archivedHidden').on( 'click', function (e) {
        e.preventDefault();
    
        // Get the column API object
        var column = accountUpdateTable.column(6);
    
        // Toggle the visibility
        column.visible( ! column.visible() );
    
        if($(this).text().trim() == 'Archived Hidden' ){
            $(this).text('Archived Shown');
            sessionStorage.setItem('ssArchived', "Shown");
    
        }else{
             $(this).text('Archived Hidden');
             sessionStorage.setItem('ssArchived', "Hidden");
        }
    } );
    
This discussion has been closed.