DataTable : Add checkbox in jquery datatable and handle button event


DataTable : Add checkbox in jquery datatable and handle button event


How to add checkbox in jquery datatable and how to manage selected list on button click event. Solution is below,

HTML

 <fieldset class="clearfix fs-border">
            <legend class="fs-border">User's List:</legend>
            <div class="box-body">
                <table id="myTable" class="display responsive table table-striped dataTable no-footer" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th class="text-center"><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>Mobile</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                </table>
                <input type="button" id="btnSubmit" value="Submit Data" class="btn btn-default" />
            </div>
        </fieldset>

JQuery:

 var table = "";
var count = 0;
var totalCount = 0;
var checkedCount = 0;
 
$(document).ready(function () {
    $("#messagebox").hide();
    table = $("#myTable").DataTable({
        "processing"true,
        "serverSide"true,
        "filter"true,
        "orderMulti"false,
        "paging"true,
        "responsive"true,
        "ajax": {
            "type""POST",
            "url""ControllerName/GetJsonData",
            "dataSrc"function (data) {
                //Make your callback here.                
                if (data.value == "fail") {
                    window.location = "Unauthorised";
                } else {
                    //console.log(data);
                }
                countall(data.data);
                return data.data;
            }
        },
        "columnDefs": [{
            "targets": 0,
            "searchable"false,
            "orderable"false,
            "className""dt-body-center",
            "render"function (data, type, full, meta){
                return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
            }
        }],
        "order": [[1, "asc"]],
        "columns": [
            {
                data: null,
                orderable: false,
                width: 100,
                render: function (data, type, row) {
                    //console.log(data);
                    return "<input type='checkbox' id='" + data.userId + "'> "
                }
            },
               { "data""FirstName""name""FirstName" },
               { "data""LastName""name""LastName" },
               { "data""Email""name""Email" },
               { "data""Mobile""name""Mobile" },
               { "data""Status""name""Status" },
        ]
       
    });
 
    function countall(data)
    {
        totalCount =  data.length;        
    }
 
    // Handle click on "Select all" control
    $('#example-select-all').on('click'function () {
        // Get all rows with search applied
        var rows = table.rows({ 'search''applied' }).nodes();
        // Check/uncheck checkboxes for all rows in the table
        $('input[type="checkbox"]', rows).prop('checked'this.checked);
    });
 
    // Handle click on checkbox to set state of "Select all" control
    $('#myTable tbody').on('change''input[type="checkbox"]'function () {
        // If checkbox is not checked
        if (!this.checked) {
            var el = $('#example-select-all').get(0);
            // If "Select all" control is checked and has 'indeterminate' property
            if (el && el.checked && ('indeterminate' in el)) {
                // Set visual state of "Select all" controlas 'indeterminate'
                el.indeterminate = true;
            }
        }

      /// Set select all checkbox tick and untick
       checkedCount=0;
       table.$('input[type="checkbox"]').each(function () {
           if (this.checked) {                
               checkedCount++;               
               if(totalCount==checkedCount)
               {                    
                   $('#push-select-all').prop("indeterminate"false);
                   $('#push-select-all').prop('checked'true);
               }
           }            
       });

    });
 
 
    // Handle send event for selected users
    $('#btnSubmit').on('click'function (e) {
         
        var membersList = [];
            
        // Iterate over all checkboxes in the table
        table.$('input[type="checkbox"]').each(function () {        
            if (this.checked) {
                membersList.push({ userId: $(this).attr('id') });
                //console.log($(this).attr('id'));
                count++;
            }
        });
 
        if (count == 0)
        {
            alert("Please select atleast one user to submit data.");
        } 
        else {
            $.ajax({
                type: "POST",
                url: "ControllerName/ActionMethodName",
                contentType: 'application/json',             
                data: "{userList :" + JSON.stringify(membersList) + ",message :\"" + $("#Message").val() + "\"}",
                success: function (retdata) {                    
                    if (retdata == "success")
                        alert("Message sent successfully.");
                    else
                        alert(retdata);
                    
                }
            });
        }
       
    }); 
});

 

C# Code:

 [HttpPost]
        public JsonResult ActionMethodName(List<VMUsers> userList, string message)
        {
            var returnMessage = "business return message";
 
            return Json(returnMessage, JsonRequestBehavior.AllowGet);
        }
 
public class VMUsers
   {
       public string userId { getset; }
   } 


Enjoy !!!

 :)

No comments:

Post a Comment