【问题标题】:67 dynamic checkboxes, how to disable all check boxes after 4 have been selected?67个动态复选框,4个被选中后如何禁用所有复选框?
【发布时间】:2018-12-26 03:14:09
【问题描述】:

我有 67 个复选框,我只想让用户从这 67 个中选择 4 个。我现在的问题是:我不知道如何收听复选框,然后查看它们是否已被选中 4 个。

<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp" id="catTable">
<tbody style="width: 80%;">
    <tr style="width: 50%;">
        <?php
        $countCat = ceil(count($categories) / 11);
        $i = 0;
        foreach ($categories as $key => $value) {

            ?>

            <?php if ($i % $countCat == 0) { ?></tr><tr><?php } ?>

            <td class="mdl-data-table__cell--non-numeric">
                <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="<?php print $value['catID']; ?>">
                    <input type="checkbox" id="<?php print $value['catID']; ?>" class="mdl-checkbox__input">
                    <span class="mdl-checkbox__label"><?php print $value['categoryNames']; ?></span>
                </label>
            </td>


            <?php
            ++$i;
        }

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

我尝试过的:(JQuery)

   var checkboxes = ''; // Not sure how to get the random 67 that have been selected.
if (checkboxes == 4) {
    $('#catTable').html('');
    $('#catTable').html(''); // create new table with the selected 4
}

是否可以使用 Jquery 来监听复选框,一旦选择了 4 就删除表并保留选择的 4。如果用户想要删除或添加不同的类别,那么创建一个删除或添加按钮来恢复类别表?

提前致谢

【问题讨论】:

  • 是的,这是可能的。你试过什么?
  • 现在更新帖子
  • 发布更新,虽然我被困在主要部分,试图选择在哪里选择的 id ?
  • 我在我的代码中添加了一个按钮,它将所有选中的复选框值编译成一个数组并将其打印到控制台。应该很容易适应您自己的核心结构。希望对你有帮助

标签: php jquery html


【解决方案1】:

这段代码怎么样:

var limit = 4;
$('input.mdl-checkbox__input').on('change', function(evt) {
  if ($('input.mdl-checkbox__input:checked').length > limit) {
    this.checked = false;
  }
});

我认为这段代码的循环会更短。

【讨论】:

  • 我尝试记录var limit,如果选中这些框,它不会显示任何内容?
  • var limit 只是一些限制框。它可以用来与$('input.mdl-checkbox__ input:checked')进行比较。长度,当检查检查时,复选框大于限制,请取消选中该复选框。勾选与否都不会改变
  • 即使 PHP 或 javascript 已经检查了某些框,我的解决方案也能正常工作。如果您觉得这有帮助并且比其他答案更好,请将我的答案标记为已接受的答案,谢谢!
  • 测试了小提琴,它按预期工作,但在我看来,它允许我选择 4,但我也可以选择超过 4 个,而无法删除选定的。我可以选择超过 4 个并且无法删除任何
  • 也许你还有另一个 js 代码与某个地方的复选框相关联,如果没有,这段代码可以正常工作。
【解决方案2】:

下面的代码可以按照您的意愿行事,检查任何动态创建的复选框上的更改事件。它只作用于包装在具有.checkbox-group 类且属性为checkbox-limit 的元素中的复选框。这样,代码可以应用于具有不同限制的单个页面上的多个复选框列表,但除非指定了限制,否则不会触发。

只有选中的复选框在达到限制后仍处于启用状态(因此您可以取消选择它们并根据需要选择另一个)。

我为每个组添加了一个按钮,演示如何收集归因于给定选定复选框的值。

比其他一些答案更复杂...所以它可能有点过分,但也更通用/更强大。

希望对你有帮助。


演示

// Add change event trigger dynamically
$(document).on('change', '.checkbox-group[checkbox-limit] input[type="checkbox"]', function() {

  // Get limit from wrapper attribute
  var lim = $(this).closest(".checkbox-group").attr("checkbox-limit");

  // Get current number of selected checkboxes within this wrapper
  // You could change .find() for .children() to prevent it checking through the entire tree within the wrapper.
  var selCount = $(this).closest(".checkbox-group").find("input[type='checkbox']:checked").length

  // Check number of checked checkboxe against limit
  if (selCount == lim) {

    // Disable unchecked checkboxes (so user can still uncheck selected checkboxes)
    $(this).closest(".checkbox-group").find("input[type='checkbox']:not(:checked)").attr("disabled", true);

  } else {

    // Enable checkboxes if a checkbox is unchecked 
    $(this).closest(".checkbox-group").find("input[type='checkbox']:not(:checked)").removeAttr("disabled");

  }

});


// Add click event to gather values button
$(".gatherValues").click(function() {

  // Setup array to save values to
  var selValues = [];

  // Cycle through all checked checkboxes within that group
  $(this).closest(".checkbox-group").find("input[type='checkbox']:checked").each(function() {

    // Add value to array
    selValues.push($(this).attr("value"));

  });

  // Print to console
  console.log(selValues);

})
.checkbox-group {
  border-left: 5px solid grey;
  border-bottom: 1px dashed grey;
  padding: 10px 10px 10px 20px;
  margin-bottom: 20px;
}

button {
  margin: 20px 00px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="checkbox-group" checkbox-limit="4">

  <p>Limit of 4 selection for this group.
  </p>

  <input type="checkbox" value="A">A<br>
  <input type="checkbox" value="B">B<br>
  <input type="checkbox" value="C">C<br>
  <input type="checkbox" value="D">D<br>
  <input type="checkbox" value="E">E<br>
  <input type="checkbox" value="F">F<br>

  <button class="gatherValues">Compile Values</button>

</div>

<div class="checkbox-group">

  <p>No limit for this group, check does not fire as the .checkbox-group wrapper does not have a checkbox-limit attribute.</p>

  <input type="checkbox" value="1">1<br>
  <input type="checkbox" value="2">2<br>
  <input type="checkbox" value="3">3<br>
  <input type="checkbox" value="4">4<br>

  <button class="gatherValues">Compile Values</button>


</div>

<div class="checkbox-group" checkbox-limit="1">

  <p>Limit of 1 selection for this group.
  </p>

  <input type="checkbox" value="Option 1">Option 1<br>
  <input type="checkbox" value="Option 2">Option 2<br>
  <input type="checkbox" value="Option 3">Option 3<br>
  <input type="checkbox" value="Option 4">Option 4<br>

  <button class="gatherValues">Compile Values</button>

</div>

【讨论】:

  • 我用.map()函数代替$('input.mdl-checkbox__input:checked').map(function() { return $(this).val(); }).get();
【解决方案3】:

这将计算选中复选框的数量:

var selected_checkbox = 0;

//listen for checkbox change event, then count number of selected. put this inside document ready.
$('input[type=checkbox]').change(function(){ 
   $('input[type=checkbox]').each(function () {
      if($(this).is(":checked")){
         selected_checkbox ++;
      }

      if selected_checkbox == 4 then
          //hide the selection box here

          return false; //exit the checkbox loop
      }
   });
});

【讨论】:

  • 我尝试将$('input[type=checkbox]').addClass('disabled'); 添加到if 语句selected_checkbox == 4 中,结果我认为这可能是处理@NdifrekeEkim 所说的大量复选框的不好方法。用户可以选中和取消选中任何复选框,它可能会损坏。
  • 禁用选中的 4 个复选框不是一个好主意,您可以隐藏选择列表或提示用户选择超过最大值时仅选择 4 个。
【解决方案4】:

我会说保留一个全局变量,每次发生复选框事件时都会增加该变量。然后在全局变量大小为 4 时禁用默认的 a 操作。

请记住,用户可能会取消选中已选中的框,因此您应该处理此类情况,以便全局变量不会在此类事件中增加。

全局变量很讨厌,但这应该可以让你抢先一步

【讨论】:

  • “请记住,用户可能会取消选中已选中的框,因此您应该处理此类情况,以便全局变量不会在此类事件中增加。”。我正在尝试解决 x_x
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2015-12-20
相关资源
最近更新 更多