只允许选中一个复选框是带有复选框列的数据表吗?

时间:2015-07-02 12:54:24

标签: jquery datatables

我正在使用jQuery数据表来显示一些表格数据,并将复选框列作为第一列。

<div>
    <table style="width:100%" id="resultsTable" class="table table-striped table-bordered">
        <thead>
            <tr>
                <th></th>
                <th>
                    Approve
                </th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
function BindData() {
    $('#resultsTable').DataTable({
        "sAjaxSource": "/Jumbo/GetallResults",
        "bProcessing": true,
        "bStateSave": true, 
        "aoColumns": [{
            "sName": "",
            "sClass": "checkbox-column",
            "mRender": function () {
                return ' <input type="checkbox" />';
            }
        },{
            "sName": "Colors",
            "bSortable": true,
            "mRender": function (data,type, full) {
                return '<span title=\"' + full[0] + '\">' + full[0] + '</span>';
            }
        }]
    });
}

$('#resultsTable').on('change','.check', function() {
    var $checkboxes = $('#resultsTable').find('.check');
    var $checked = $checkboxes.filter(function() { return this.checked; });
});

呈现一个网格,其中每一行在第一列中都有一个复选框。

我需要一种方法让它以这样的方式工作:在任何给定的实例中,只允许检查一个复选框。

有人可以指导我完成这件事吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

做了一个小例子。

$(function () {
  $("input").change(function (e) {
    e.preventDefault();
    if ($(this).is(":checked")) {
      $("input").prop("checked", false);
      $(this).prop("checked", true);
    }  
  });
});
* {margin: 0; padding: 0; list-style: none; font-family: 'Segoe UI';}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
  <li><input type="checkbox"> Item 1</li>
  <li><input type="checkbox"> Item 2</li>
  <li><input type="checkbox"> Item 3</li>
  <li><input type="checkbox"> Item 4</li>
  <li><input type="checkbox"> Item 5</li>
</ul>

答案 1 :(得分:0)

在数据表中使用以下内容

   columnDefs: [ {
           orderable: false,
           className: 'select-checkbox',
           targets:   0
       } ],
       select: {
           style:    'os',
           selector: 'td:first-child'
       },
      "aoColumns": [
       {"mData": "id", "mRender" : function(data) { return "";} },
       {"mData": "name"},
       {"mData": "age" },
       {"mData": "gender"},

     ],

获取所选数据:

 var oTable = $('#yourTableId').dataTable();
      $('#yourTableId tbody tr').each(function(index,elem){
        if($(this).hasClass("selected")){
            var aData = oTable._('tr')[index];

         }
     });

HTML

                   <thead>
                     <tr>
                        <th width="10%"></th>
                        <th width="25%">Name</th>
                        <th width="20%" >Age</th>
                        <th width="45%" >Gender</th>
                     </tr>
                  </thead>