【问题标题】:DataTables - checkbox with 'onchange' not workingDataTables - 带有“onchange”的复选框不起作用
【发布时间】:2021-06-09 04:58:35
【问题描述】:

我正在使用 dataTables 并希望包含一个复选框,该复选框将在更改时更新我的​​数据(选择、取消选择)。数据显示在表格中,每行都有复选框;但是:

  1. this.checked 无法识别(返回“未定义”);和
  2. 当我选中或取消选中复选框时,控制台日志中出现错误:Uncaught SyntaxError: Unexpected token ','

代码是:

{data: null,
  className: "center",
  render: function(data,type,row) {
      return ("<input type='checkbox' id=" + data.cdId + " name='update' onchange='ymActivityPatrolFunction(" + data.cdId + ", " + this.checked + ")' style='zoom: 2.0;'>")
     },
},

这给出了:

【问题讨论】:

    标签: jquery datatables


    【解决方案1】:

    您只能在函数中传递this,然后要获取其他值,您可以使用attr("id") 获取cdId 值和checked 获取检查值,即:真/假。

    演示代码:

    var data = [{
        "cdId": "1gh",
        "name": "Tiger Nixon",
      },
      {
        "cdId": "2htf",
        "name": "Garrett Winters"
      },
    
    ];
    
    
    var table = $('#example').DataTable({
      data: data,
      columns: [{
          targets: 0,
          data: "cdId",
          render: function(data, type, row) {
            //use only `this` and change data to `data.cdId` this is for dmo only..
            return ("<input type='checkbox' id=" + data + " name='update' onchange='ymActivityPatrolFunction(this)' style='zoom: 2.0;'>")
          },
          className: "center"
        },
        {
          "data": "name"
        }
      ]
    });
    
    function ymActivityPatrolFunction(checkeds) {
      //get id..and check if checked
      console.log($(checkeds).attr("id"), checkeds.checked)
    
    }
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.css" />
    <script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.js"></script>
    <table id="example" class="table table-striped table-bordered" width="100%">
      <thead>
        <tr>
          <th>Checkbox</th>
          <th>Name</th>
    
        </tr>
      </thead>
    
      <tfoot>
        <tr>
          <th>Checkbox</th>
          <th>Name</th>
    
        </tr>
      </tfoot>
    
    </table>

    【讨论】:

    • 很高兴为您提供帮助:)
    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    相关资源
    最近更新 更多