如何使用 JavaScript HTML 在多行 table 中通过复选框启用下拉列表

How to enable Dropdownlist by Checkbox in multirow table using JavaScript HTML

我要控制the dropdownlist to be enabled when the checkbox is checked by respective rows. 我目前的进度我设法启用和禁用下拉列表,但它不受相应行的控制。

只要选中该复选框,所有下拉列表都会启用。

php 代码部分来自 html:

<td>
    <select class="selection" name="lotDist[]" > 
    <option></option>';

    ==== sql queries in here ====

    while ($row2 = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
    {
        echo '
        <option value="'.$row["LotNo"].' / '.$row2["Grouping"].' - '.$row2["InBulkForm"].'"> 
        '.$row2["Grouping"].' - '.$row2["InBulkForm"].'</option> ';
    }  
    echo '
    </select>
</td>
<td>'.$row["LoadingWeek"].'</td>
<td>                   
    <input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row["LotNo"].'" '.$check.'>
</td>



<script>    
    $(document).ready(function() {
        $('.selection').attr('disabled', 'disabled');

        var $checkBox = $('.chkBox');

        $checkBox.on('change', function(e) {
            //get the previous element to us, which is the select
            var $select = $('.selection')

            if (this.checked) {
                $select.removeAttr('disabled');
            } else {
                $select.attr('disabled', 'disabled');
            }
        });
    });
</script>

$(this).closest('tr').find('.selection');你可以找到相应的select框属于更改复选框的行。

closest() 函数查找与 selector 匹配的第一个父项。由于您使用的是 table,我们可以 select 带有 tr select 的行,或者在该行中找到相应的 select 元素。

还更改了 select 框的启用和禁用方式。最好更改 属性 然后更改属性。而且代码也更短。不过你的方法也行。

$(document).ready(function() {
  $('.selection').attr('disabled', 'disabled');

  var $checkBox = $('.chkBox');

  $checkBox.on('change', function(e) {
    var $select = $(this).closest('tr').find('.selection');

    $select.prop('disabled', !this.checked);

    /* This works too but its better to change the property and the code is shorter when using the this.checked boolean.
    
    if (this.checked) {
      $select.removeAttr('disabled');
    } else {
      $select.attr('disabled', 'disabled');
    }
    
    */
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="selection" name="lotDist[]">
        <option>1</option>
        <option>2</option>
      </select>
    </td>
    <td>week</td>
    <td>
      <input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
    </td>
  </tr>
  <tr>
    <td>
      <select class="selection" name="lotDist[]">
        <option>1</option>
        <option>2</option>
      </select>
    </td>
    <td>week</td>
    <td>
      <input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
    </td>
  </tr>
</table>