【问题标题】:Implementing checkbox selection in datatables with Json data source使用 Json 数据源在数据表中实现复选框选择
【发布时间】:2016-06-13 19:09:31
【问题描述】:

我正在尝试使用我的数据表中的复选框来实现多行选择,但似乎无法让复选框出现。

我逐字阅读这篇文章 http://www.gyrocode.com/articles/jquery-datatables-how-to-add-a-checkbox-column/,这很有帮助,但我不知道从这里开始做什么。

之前我使用一列的 innerHTML 来为每一行保存一个复选框,但现在我需要能够选择多行,我认为最好使用经过验证的东西,就像文章中的示例一样。

反正我之前是这样的:

    $(document).ready(function () {
        var userData = @Html.Raw(Model.EditUserGroupListJson);
        var table = $('#viewUsers').DataTable({
            "data": userData,
            "columns": [
                { "title": "Email" },
                { "title": "Full Name" },
                { "title": "Member" }
            ],

            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var tblTds = $('>td', nRow);
                $(nRow).attr("id", 'tblRow_' + aData[2]);

                if (aData[3] == '0')
                {
                    tblTds[2].innerHTML = '<td><input type="checkbox" name="enrolstatus" value="' + aData[2] + '" id="' + aData[2] + '" onclick="Member(' + aData[2] + ')" /><label for="' + aData[2] + '"></label></td>';
                }
                else
                {
                    tblTds[2].innerHTML = '<td><input type="checkbox" name="enrolstatus" value="' + aData[2] + '" id="' + aData[2] + '" checked="checked" onclick="Member(' + aData[2] + ')" /><label for="' + aData[2] + '"></label>></td>';
                }
            }
        })
    });

现在:

    $(document).ready(function () {
        var userData = @Html.Raw(Model.EditUserGroupListJson);
        var table = $('#viewUsers').DataTable({
            'data': userData,
            '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']],

            'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull){
                var tblTds = $('>td', nRow);
                $(nRow).attr("id", 'tblRow_' + aData[3]);
            }
        });

        //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 or uncheck boxes 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
        $('#example 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' control as indeterminate
                    el.indeterminate = true;
                }
            }
        });

        //handle form submission event
        $('#frm-example').on('submit', function(e){
            var form = this;

            //iterate over all checkboxes in the table
            table.$('input[type="checkbox"]').each(function(){
                //if checkbox doesnt exist in DOM
                if(!$.contains(document, this)){
                    //if checkbox is checked
                    if(this.checked){
                        //create hidden element
                        $(form).append(
                            $('<input>')
                                .attr('type', 'hidden')
                                .attr('name', this.name)
                                .val(this.value)
                            );
                    }
                }
            });
        });
    });

我的html:

    <table id="viewUsers" class="display table table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th><input name="select_all" value="1" id="example-select-all" type="checkbox"></th>                  
                <th>Email</th>
                <th>Full Name</th>
                <th>Member</th>
            </tr>
        </thead>
    </table>

json:

select new string[] {"", user.Email, user.Forename + ' ' + user.Surname, user.UserID.ToString(), user.CategoryMaps.Where(c => c.CategoryID == id).Count().ToString() };

// if ticked, AddUser, otherwise RemoveUser
function Member(userID) {
    var fullURL = document.URL;
    var url = fullURL.split('EditUserGroup/');
    var categoryID = url[1];
    var postData = { 'userId': userID, 'categoryID': categoryID };
    if ($("#" + userID).is(':checked')) {
        $.post('/Admin/AddCategoryUser/', postData, function (data) {});
    }
    else {
        $.post('/Admin/RemoveCategoryUser/', postData, function (data) {});
    }
};

我还在 JSON 的开头放置了一个空白“”以允许复选框(我认为),我现在很卡住。

任何帮助将不胜感激,谢谢。

最新代码

JS:

$(document).ready(function () { var userData = @Html.Raw(Model.EditUserGroupListJson);

    var table = $('#viewUsers').DataTable({
        'data': userData,
        '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'],
        "createdRow": function (row, data, dataIndex) {
            $(row).attr("id", "tblRow_" + data[0]);
        }
    });

    // handle select all click control
    $('#example-select-all').on('click', function () {
        // check/uncheck all checkboxes in the table
        var rows = table.rows({ 'search': 'applied' }).nodes();
        $('input[type="checkbox"]', rows).prop('checked', this.checked);
    });

    // handle click on checkbox to set state of select all control
    $('#example 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 control as interminate
                el.indeterminate = true;
            }
        }
    });

    $('#frm-example').on('submit', function (e) {
        var form = this;

        // iterate over all checkboxes in the table
        table.$('input[type="checkbox"]').each(function () {
            // if checkbox doesn't exist in DOM
            if (!$.contains(document, this)) {
                // if checkbox is checked
                if (this.checked) {
                    // create a hidden element
                    $(form).append(
                        $('<input>')
                            .attr('type', 'hidden')
                            .attr('name', this.name)
                            .val(this.value)
                    );
                }
            }
        });

        //testing only

        // output form data to console
        $('#example-console').text($(form).serialize());
        console.log("Form submission", $(form).serialize());

        // prevent actual form submission
        e.preventDefault();
    });
});

HTML:

用户组成员身份

        <form id="frm-example" @*action="path/to/script"*@ method="post">
        <table id="viewUsers" class="display table table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th><input name="select_all" value="1" id="example-select-all" type="checkbox"></th>
                    <th>Email</th>
                    <th>Full Name</th>
                </tr>
            </thead>
        </table>
        <p>Press <b>Submit</b> to add selected users to user group.</p>
            <p><button>Submit</button></p>

            <pre id="example-console"></pre>
        </form>

【问题讨论】:

  • 你能附上你收到的 JSON 吗?
  • 完成,谢谢@Stargazer

标签: javascript jquery checkbox datatables


【解决方案1】:

您的 JSON 响应很可能不正确。使用您的表结构,它应该是:

var userData = [
   [ "UserId", "Email", "Full Name", "Member" ],
   [ "UserId", "Email", "Full Name", "Member" ]
];

第一个值UserId 将用作复选框的值。

要将 ID 分配给 tr 元素,请改用以下代码:

"createdRow": function(row, data, dataIndex){
   $(row).attr("id", "tblRow_" + data[0]);
}

有关代码和演示,请参阅this jsFiddle

【讨论】:

  • 非常感谢,不知道怎么漏掉了id对应的userid。至于将 id 分配给 tr 元素,您能用简单的英语向我解释一下那段代码吗?
  • @bjjrolls,我是您提到的文章的作者。有关代码和演示,请参阅 this jsFiddle
  • 另外,在调用一个 JS 函数之前,我一直在复选框上使用 onclick,该函数将 url 拆分为收集 userID 和 categoryID,基本上如果选中该框,则转到 AddUser 控制器,否则为 RemoveUser .我现在将编辑我的原始问题以包含此功能。顺便说一句,我一直在工作的网站的作者直接回复了,真是太酷了。
  • @bjjrolls,代码中的每个复选框都有一个 change 处理程序。只需在此处理程序$('#example tbody').on('change', 'input[type="checkbox"]', function(){ 中调用Member(this.value)
  • 太棒了,谢谢。我感到困惑的是
    的语法(和使用)这是指哪个脚本,又叫什么名字?
【解决方案2】:

这里正在工作fiddle

我只更改了 var userData。应该是这样的。需要身份证。

var userData = [
      [
         "1",
         "Tiger Nixon",
         "System Architect",
         "Edinburgh"
      ],
      [
         "2",
         "Garrett Winters",
         "Accountant",
         "Tokyo"
      ],
      [
         "3",
         "Ashton Cox",
         "Junior Technical Author",
         "San Francisco"
      ]
]

【讨论】:

  • 感谢您的提琴,帮助很大。关于表单操作的一个问题:
    这是指什么路径?我应该给我的整个数据表函数一个从 $(document).ready(function () { var userData = @Html.Raw(Model.EditUserGroupListJson); var table = $('#viewUsers').DataTable({ ' data': userData, 'columnDefs': [{......... ....... 并像 javascript:functionName() 一样调用它?
  • 1. action="/path/to/your/script" - 这是处理表单数据的脚本的路径。这是详细信息w3schools.com/tags/att_form_action.asp 2. $(document).ready - 这意味着脚本仅在加载 DOM 后才开始工作。您需要加载 DOM 才能找到此类元素,例如 $('#viewUsers') 和其他元素。当 DOM 未加载时,您将找不到它们。更多详情w3schools.com/jquery/event_ready.asp
  • 感谢阅读,我现在明白了。我现在的问题是让复选框出现在标题中,我已经尝试了整个下午并且无法管理它。根据我在我的问题中的最新代码更新,您是否可以看到任何可以解释原因的东西?感谢您的帮助
  • 这里,在此示例中gyrocode.com/articles/… 标题中还有一个复选框 - 此复选框选择表中的所有行。你不需要这个功能吗?
  • 我在这里没有找到合适的选项datatables.net/manual/options 来禁用标题复选框(我认为这不是一个好主意)但是如果你需要你可以用 .css 来做 - 看这里jsfiddle.net/HellLena/hayd86mn/4
猜你喜欢
  • 2016-11-09
  • 2015-05-22
  • 2012-08-16
  • 1970-01-01
  • 2020-11-20
  • 2014-08-09
  • 1970-01-01
  • 2013-02-05
  • 2013-12-01
相关资源
最近更新 更多