laravel - 在提交的数据表中获取所有选中的项目

时间:2017-08-28 07:21:59

标签: php jquery datatables laravel-5.2

我有一个步骤表单,其中包含jQuery数据表中的项列表。用户将使用复选框选择所需的项目,然后单击下一步,将显示所选项目以进行最终确定。这是通过ajax(form.serialize)完成的。但是,只有在活动页面上选择的项目才会被考虑。正在显示第2页,只有该页面中的复选框已提交

我使用foreach来获取已检查的项目

foreach($request->input('ItemNo') as $key => $item_no)

这是我的表

<table id="supplies_t" class="table table-striped">
  <thead>
    <tr>
      <th><input class="main_chkbx" name="main_chkbx" type="checkbox"></th>
      <th>Item Name</th>
      <th>Description</th>
      <th>Unit</th>
    </tr>
  </thead>
  <tbody>
    @if(isset($supplies))
      @foreach($supplies as $supply)
        <tr id="{{ $supply->ItemName }}">
          <td><input name="ItemNo[]" class="ind_chkbx" value="SUPPLY-{{ $supply->SupplyNo }}" type="checkbox"></td>
          <td>{{ $supply->ItemName }}</td>
          <td>{{ $supply->Description }}</td>
          <td>{{ $supply->UnitName }}</td>
        </tr>
      @endforeach
    @endif
  </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

原因

jQuery DataTables出于性能原因从DOM中删除不可见的行。提交表单时,只有可见复选框的数据会发送到服务器。

解决方案是使用$() API方法来访问表中的所有元素。

解决方案1.提交表格

在提交表单时,您需要将已检查且在DOM中不存在的元素<input type="checkbox">转换为<input type="hidden">

var table = $('#example').DataTable({
   // ... skipped ...
});

$('form').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)
            );
         }
      } 
   });          
});

解决方案2:通过Ajax发送数据

var table = $('#example').DataTable({
   // ... skipped ...
});

$('#btn-submit').on('click', function(e){
   e.preventDefault();

   $.ajax({
      url: '/path/to/your/script.php',
      data: table.$('input[type="checkbox"]').serialize();
   }).done(function(data){
      console.log('Response', data);
   });
});

样本

有关详细信息和演示,请参阅jQuery DataTables: How to submit all pages form data