通过在输入框中插入行数来选择多行复选框

Posted

技术标签:

【中文标题】通过在输入框中插入行数来选择多行复选框【英文标题】:get selected multiple rows of checkbox by inserting no of rows in input box 【发布时间】:2021-08-24 17:00:04 【问题描述】:

如何通过输入数字来获得数据表的选中复选框

我正在尝试编写一个bootstrap data table,它能够选择行的复选框 inserting no of rows in the input box

我不知道该怎么做。

例如:我在输入框中输入了数字然后在[开头->自动选中两行的复选框表没问题]

<!DOCTYPE html>
<html><head>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
        <script src="//code.jquery.com/jquery.js"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>    
        <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>


</head>
<body>
<div class="container text-center">
<label for="fname">insert number for select multiple check box</label>
<input type="number" id="selectcheckbox" name="selectcheckbox">
<table data-toggle="table" 
       data-classes="table table-hover table-condensed"
       data-row-style="rowColors"
       data-striped="true"
       data-sort-name="Quality"
       data-sort-order="desc"
       data-pagination="true"
       data-click-to-select="true"
       >
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th class="col-xs-1" data-field="Product_Name" data-sortable="true">Product Name</th>
        <th class="col-xs-1" data-field="Quality" data-sortable="true">Quality</th>
        <th class="col-xs-6" data-field="Quantity" >Quantity</th>
    </tr>
    </thead>
    <tbody>
   <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Wheat</td>
        <td>Good</td>
        <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Rice</td>
        <td>Good</td>
        <td>100 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Rice</td>
        <td>Good</td>
        <td>100 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr>            
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Maze</td>
        <td>Fine</td>
        <td>10 Packs</td>
    </tr>            
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr> 
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr> 
    <tr id="tr-id-2" class="tr-class-2">
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr> 
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr> 
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr> 
    <tr id="tr-id-2" class="tr-class-2">
        <td></td>
        <td>Sugar</td>
        <td>Prime</td>
        <td>200 Bags</td>
    </tr>        
    </tbody>    
</table>
</div>

<script>
function queryParams() 
    return 
        type: 'owner',
        sort: 'updated',
        direction: 'desc',
        per_page: 100,
        page: 1
    ;

function rowColors(row, index) 
    var classes = ['active', 'success', 'info', 'warning', 'danger'];
    
    if (index % 2 === 0 && index / 2 < classes.length) 
        return 
            classes: classes[index / 2]
        ;
    
    return ;

</script>

</body>
</html>

我的实际代码在这里

<html>
<body>
<label for="fname">insert number for select multiple check box</label>
    <input type="number" id="selectcheckbox" name="selectcheckbox">
<table class="table table-striped table-bordered" id="tbl">
    <thead>
        <tr>
        <th>SELECT check box is here</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        <th>Value</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script>
$(document).ready(
    function()
    
            var table = $('#tbl').DataTable(
            "columnDefs": 
            [
            
                orderable: false,
                className: 'select-checkbox',
                targets:   0
            
            ],
          destroy:true,
          "fnRowCallback" : 
          function(nRow, aData, iDisplayIndex)
          
              $("td:first", nRow).html(iDisplayIndex +1);
              return nRow;
          ,      
          'select': 
          
              style: 'multi',
              selector:'td:nth-child(1)'
          ,
              'order': [[ 1, 'asc' ]],
          );
          
          $.ajax(
          type:"POST", 
          url:"fetch_data.php",  
          data:'value='+value,
            success: function(data)
            
              if(data['error'] == '0')
              
                console.log(data);
                  
                  //set Finish Data
                  table.clear().draw();
                  for(i = 0; i < data['chemical_date'].length; i++) 
                  
                    table.row.add([
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                    data['chemical_date'][i]['value'],
                
                    "<input type='text' value='' class='form-control' id='selectedqty"+i+"' onkeyup='sqty(this.id);' name='selectedqty"+i+"'/>",
                    "<input type='text' value='' class='form-control ' id='note"+i+"'  name='note"+i+"' />",
                    "<input type='text' value='' class='form-control ' id='location"+i+"'  name='location"+i+"' />",
                    '',
                    '',
                    ''
                    ]).draw(false);
                  
              
            
          )
    );
</script>
</body>
</html>

fetch_data.php

<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST')

    extract($_POST);
    //Top data
        $data = array();
        $obj = array(); 
        $sql = "some query here...";

            $result = mysqli_query($db, $sql);
            $chemical = array();
        
            while ($row = mysqli_fetch_assoc($result)) 
            
                //Finish Data
                $row1 = array();
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                $row1['value'] = $row['value'];
                array_push($chemical, $row1);
                //Stock Data
            
            $response['chemical_date'] = $chemical;
            //Process Data
            $response['error'] = "0";

else
    $response['error'] = "1";
    echo json_encode($response);
?>

【问题讨论】:

【参考方案1】:

您可以使用 for 循环,然后在其中使用 :eq() 根据索引值选中复选框。

演示代码

function queryParams() 
  return 
    type: 'owner',
    sort: 'updated',
    direction: 'desc',
    per_page: 100,
    page: 1
  ;


function rowColors(row, index) 
  var classes = ['active', 'success', 'info', 'warning', 'danger'];

  if (index % 2 === 0 && index / 2 < classes.length) 
    return 
      classes: classes[index / 2]
    ;
  
  return ;


$("#selectcheckbox").on("change", function() 
  $("[name=btSelectItem]").prop("checked", false) //unchecked..
  //loop
  for (let i = 0; i < $(this).val(); i++) 
    //if that elemnt exist
    if ($("[name=btSelectItem]:eq(" + i + ")").length > 0) 
      $("[name=btSelectItem]:eq(" + i + ")").prop("checked", true) //checked it
    
  

)
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="//code.jquery.com/jquery.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>

<label for="fname">insert number for select multiple check box</label>
<input type="number" id="selectcheckbox" name="selectcheckbox">
<table data-toggle="table" data-classes="table table-hover table-condensed" data-row-style="rowColors" data-striped="true" data-sort-name="Quality" data-sort-order="desc" data-pagination="true" data-click-to-select="true">
  <thead>
    <tr>
      <th data-field="state" data-checkbox="true"></th>
      <th class="col-xs-1" data-field="Product_Name" data-sortable="true">Product Name</th>
      <th class="col-xs-1" data-field="Quality" data-sortable="true">Quality</th>
      <th class="col-xs-6" data-field="Quantity">Quantity</th>
    </tr>
  </thead>
  <tbody>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Wheat</td>
      <td>Good</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Rice</td>
      <td>Good</td>
      <td>100 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Rice</td>
      <td>Good</td>
      <td>100 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Maze</td>
      <td>Fine</td>
      <td>10 Packs</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
    <tr id="tr-id-2" class="tr-class-2">
      <td></td>
      <td>Sugar</td>
      <td>Prime</td>
      <td>200 Bags</td>
    </tr>
  </tbody>
</table>

更新 1

当您使用 select-checkbox 时,插件本身不会创建复选框,它们由 css 代码处理(添加选中)。因此,查看当我们选中任何复选框时生成的 html 后,它会将 selected 类添加到 tr,因此我们可以简单地使用 addClass("selected") 来选择并选中该行。

演示代码

$(document).ready(function() 
  var table = $('#example').DataTable(
    columnDefs: [
      orderable: false,
      className: 'select-checkbox',
      targets: 0
    ],
    select: 
      style: 'multi',
      selector: 'td:nth-child(1)'
    ,
    order: [
      [1, 'asc']
    ]
  );


  $("#selectcheckbox").on("change", function() 
    //remove selected class
    $("#example tr").removeClass("selected")
    for (let i = 0; i < $(this).val(); i++) 
      //check if td there ...
      if ($("#example td.select-checkbox:eq(" + i + ")").length > 0) 
        //add selected class..
        $("#example td.select-checkbox:eq(" + i + ")").closest("tr").addClass("selected") //try with `.click()` as well..
      

    
  )
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.3.3/css/select.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.3.3/js/dataTables.select.min.js"></script>

<input type="number" id="selectcheckbox" name="selectcheckbox">
<table id="example" class="stripe row-border order-column nowrap" style="width:100%">
  <thead>
    <tr>
      <th></th>
      <th>First name</th>
      <th>Last name</th>
      <th>Position</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td></td>
      <td>Garrett</td>
      <td>Winters</td>
      <td>Accountant</td>

    </tr>
    <tr>
      <td></td>
      <td>Ashton</td>
      <td>Cox</td>
      <td>Junior Technical Author</td>

    </tr>
    <tr>
      <td></td>
      <td>Cedric</td>
      <td>Kelly</td>
      <td>Senior Javascript Developer</td>

    </tr>
    <tr>
      <td></td>
      <td>Airi</td>
      <td>Satou</td>
      <td>Accountant</td>

    </tr>
  </tbody>
</table>

但是,我不确定这是否是正确的解决方案:)

【讨论】:

我正在使用 Jquery 数据表并使用 ajax 获取数据,而复选框 &lt;td class="bs-checkbox "&gt;&lt;input data-index="0" name="btSelectItem" type="checkbox"&gt;&lt;/td&gt; 中没有输入 我只有这个&lt;td class=" select-checkbox"&gt;1&lt;/td&gt; 之前的代码是什么?您正在使用数据表吗?但是有问题你已经添加了 boostrap 表? 你能检查一下我上面的新代码吗...是的,我以前的代码是我试图用我的旧代码实现的.. 我不确定。试试看,看看是否有效。替代方式而不是select-checkbox 使用实际复选框(在初始化数据表时创建它们)。另外,我在谷歌上没有找到任何与此相关的内容。【参考方案2】:

这应该根据数字选中每行第一个 TD 中的复选框

$('#selectcheckbox').on('input', function() 
  let num = $(this).val();
  $('.table td:first-child input[type="checkbox"]').each(function (index) 
    if (index <= num-1) $(this).prop("checked", true);
  )
)

【讨论】:

【参考方案3】:

这是一个普通 JS 中的示例。

// Grab the input, and the input boxes
const input = document.querySelector('input');
const inputs = document.querySelectorAll('table input[type="checkbox"]');

// Add an event listener to the input to watch for changes
input.addEventListener('change', handleClick, false);

function handleClick() 

  // Grab the number from the input box
  // (it's a string so you have to coerce it to a number)
  const number = Number(input.value);

  // If the number is less than or equal to the
  // number of input boxes...
  if (number <= inputs.length) 

    // ...loop through the boxes
    // and check them if they match the number
    // and uncheck them if they don't
    for (let i = 0; i < inputs.length; i++) 
      if (i < number) 
        inputs[i].checked = 'checked';
       else 
        inputs[i].checked = '';
      
    
  
<input type="number" />
<table>
  <tbody>
    <tr><td><input type="checkbox" /></td></tr>
    <tr><td><input type="checkbox" /></td></tr>
    <tr><td><input type="checkbox" /></td></tr>
    <tr><td><input type="checkbox" /></td></tr>
  </tbody>
</table>

【讨论】:

以上是关于通过在输入框中插入行数来选择多行复选框的主要内容,如果未能解决你的问题,请参考以下文章

在下拉框输入值的时候,下拉框中的值出现在下拉框中,怎么实现?

如何从数据框中选择一些具有特定行名的行? [关闭]

python如何在文本框中输入信息插入到数据库

如何更改word里的表格固定宽高

如何在复选框打勾时将一个文本框中输入的数据显示到另一个文本框?

Word中如何固定表格的宽和高