DataTables-单击功能在第一次单击时触发,第二次触发两次,第三次触发三次,依此类推

时间:2018-09-03 06:15:50

标签: jquery datatables

每次单击“ #archivedHidden”按钮时,触发切换列可见性的功能的次数就会增加一。这意味着在第一次单击上显示了存档日期列(开始为隐藏),第二次单击该列未隐藏(应为),第三次单击该列已隐藏(不应为),第四次单击该列仍为隐藏(应该是)。

$(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();

    } );
}

0 个答案:

没有答案