【问题标题】:How to get First column of Jquery Datatable as Checkbox如何将 Jquery Datatable 的第一列作为复选框
【发布时间】:2016-12-25 10:57:30
【问题描述】:

我有一个要求,我需要将第一列及其后续行值添加为选中或未选中复选框。我现在面临的问题是来自服务器端的动态数据之一。在这里,列名和行值都来自服务器端。这是代码。

   $('#SettingsDatatable').dataTable({
   "order": [],
   "dom": "Bfrtip",
   "buttons": ["copy", "csv", "excel", "pdf", "print"],
   "columnDefs": [{
   "className": "dt-center", "orderable": false, "width": 20
                        }], 
  "columns": dataObject[0].columns,
   "data": dataObject[0].data
                    });

如何添加复选框列以及如何根据dataObject[0].data 中的值选中和取消选中它?请帮忙。谢谢。

【问题讨论】:

  • 我有类似的解决方案,我生成 UI,其中行/列是从服务器端生成的。您只需要在那里实现,客户端就会相应地呈现 UI 对象。
  • @Jits 如何在来自服务器端的 Json 格式数据的情况下做到这一点?
  • 你有来自mysql表的数据吗?
  • @Jits 有什么关系?
  • 我正在为您提供答案,给我一些时间。请相应地尝试。

标签: javascript jquery checkbox datatables


【解决方案1】:

您可以使用columnDefs 来呈现自定义html

var dataObject = [{
  "columns": [{
    "title": "Select"
  }, {
    "title": "DbColumn Name"
  }, {
    "title": "UserColumn Name"
  }],
  "data": [
    ["False", "STARTDATE", ""],
    ["True", "ENDDATE", ""],
    ["False", "CLASS ", ""],
    ["True", "AUDIT_DATE ", ""]
  ]
}];

$('#SettingsDatatable').dataTable({
  "order": [],
  "dom": "Bfrtip",
  "buttons": ["copy", "csv", "excel", "pdf", "print"],
  "columnDefs": [{
    "targets": 0,
    "render": function(data, type, full, meta) {
      return '<input type="checkbox" ' + (data == 'True' ? 'checked' : '') + ' />';
    }
  }, {
    "className": "dt-center",
    "orderable": false,
    "width": 20
  }],
  "columns": dataObject[0].columns,
  "data": dataObject[0].data
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.1/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.1/css/jquery.dataTables.css" rel="stylesheet" />
<table id="SettingsDatatable"></table>

【讨论】:

  • 假设我有三列并且它的值像 ` [{"columns":[{"title":"Select"},{"title ":"DbColumn Name"},{"title":"UserColumn Name"}],"data":[["False","STARTDATE",""],["True","ENDDATE",""] ,["False","CLASS",""],["True","AUDIT_DATE",""]]}]`
【解决方案2】:

这是使用 PHP、MySQL 和 jQuery 的解决方案。请根据您的需要进行转换,例如

  1. 将您的数据库从 MySQL 更改为 Oracle。
  2. 将服务器端下拉菜单更改为使用复选框。
  3. 请提供 $settingsDatatableServer 变量的确切路径(提及代码的服务器端文件)。

客户端(jQuery):

settingsDatatable = $("#SettingsDatatable").dataTable({
    aLengthMenu: [ [10, 25, 50, 100, "-1"], [10, 25, 50, 100, "All"] ],
        iDisplayLength: 10,
        searching: true,
        "aaSorting": [],
        "order": [[ 0, "asc" ]],
        "sPaginationType": "full_numbers",

        "bProcessing": true,
        "serverSide": true,
        "bDestroy": true,
        "cache": false,
        "sAjaxSource": "<?php echo $settingsDatatableServer; ?>",

        "aoColumnDefs": [
            { "bSortable": false, "aTargets": [ 1, 2, 3, 4, 5 ] },
            { "data": "column1" },
            { "data": "column2" },
            { "data": "column3" },
            { "data": "column4" },
            { "data": "column5" },
        ],
   });

服务器端(PHP + MySQL)

<?php

if($_GET) {

    $aColumns = array( 'column1', 'column2', 'column3', 'column4', 'column5' );

    $sIndexColumn = "column1";

    $sTable = $yourtable;

    $sSql['user'] = DB_USER;
    $sSql['password'] = DB_PASSWORD;
    $sSql['db'] = DB_NAME;
    $sSql['server'] = DB_HOST;

    function fatal_error ( $sErrorMessage = '' )
    {
        header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
        die( $sErrorMessage );
    }

    if ( ! $sSql['link'] = mysqli_connect( $sSql['server'], $sSql['user'], $sSql['password']  ) )
    {
        fatal_error( 'Could not open connection to server' );
    }

    if ( ! mysqli_select_db( $sSql['link'], $sSql['db'] ) )
    {
        fatal_error( 'Could not select database ' );
    }


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
            intval( $_GET['iDisplayLength'] );
    }


    /*
     * Ordering
     */
    $sOrder = "";
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".
                    ($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'asc') .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }


    /*
     * Filtering
     */
    $sWhere = "";
    if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= "`".$aColumns[$i]."` LIKE '%". $_GET['sSearch'] ."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= "`".$aColumns[$i]."` LIKE '%". $_GET['sSearch_'.$i] ."%' ";
        }
    }


    $sQuery = "
        SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."`
        FROM $sTable
        $sWhere
        $sOrder
        $sLimit
        ";
    $rResult = mysqli_query( $sSql['link'], $sQuery ) or fatal_error( 'MySQL Query Error: ' . mysqli_errno() );

    $sQuery = "
        SELECT FOUND_ROWS()
    ";
    $rResultFilterTotal = mysqli_query( $sSql['link'], $sQuery ) or fatal_error( 'MySQL Filter Error: ' . mysqli_errno() );
    $aResultFilterTotal = mysqli_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    $sQuery = "
        SELECT COUNT(`".$sIndexColumn."`)
        FROM $sTable
    ";
    $rResultTotal = mysqli_query( $sSql['link'], $sQuery ) or fatal_error( 'MySQL Total Error: ' . mysqli_errno() );
    $aResultTotal = mysqli_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = mysqli_fetch_array( $rResult ) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ ) {

            $row[0] = '<select id=' . $aRow['column'] . "-" . $aColumns[$i] . ' class="dropdownselect" style="width:80px; color:red; font-weight:bold; text-align:left; padding-left:3px;"><option selected="selected" value="true">true</option> <option value="false">false</option></select>';
            $row[] = $aRow[ $aColumns[$i] ];

        }

        $output['aaData'][] = $row;
    }

    echo json_encode( $output );

}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多