0

我想防止用户选择超过 3 个复选框,但数据是从我的表中检索的。

即我从我的表中检索到 5 个复选框,但是当用户超过限制时我的脚本不起作用。这是我的代码。

<script type="text/javascript">
$('input[id="fruits"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
</script>

<?php
if ($result = $mysqli->query("SELECT fruitId, fruitname, fruitDes  FROM tbl_fruit")) {
if ($result->num_rows > 0)
{
echo "<table border='0' cellpadding='10'>";
echo "<tr><th>ID</th> <th>Name</th <th>Description</th> <th></th> </tr>";

while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td>" . $row->fruitId . "</td>";
echo "<td>" . $row->fruitname ." </td>";
echo "<td>" . $row->fruitDes ." </td>";
echo "<td><input type ='checkbox' name='fruits[]' value='" . $row->studId ."' id='fruits'></td>";
echo "</tr>";
}
echo "</table>"; } else {
echo "No results to display!";
}
}
else {
echo "Error: " . $mysqli->error;
}
$mysqli->close();
 ?>
4

4 回答 4

0

如果你真的想这样做,你需要先计算有多少被选中,如果它是最大数量,禁用未选中的。如果计数小于数字,则启用所有复选框:

<script type="text/javascript">

function toggleCheckboxes(name, num) {

    var checkedCount = 0;
    var boxes = document.getElementsByName(name);
    var box, disable, i;

    // If there aren't enough boxes, forget it
    if (boxes.length < num) return;

    // Count how many are checked
    for (var i=0, iLen=boxes.length; i<iLen; i++) {
      checkedCount += boxes[i].checked? 1 : 0;
    }

    // Work out if need to disable any
    disable = !!(checkedCount >= num); 

    // Only disable those that aren't checked
    // If fewer than num checked, enable them all
    for (i=0; i<iLen; i++) {
      box = boxes[i];
      box.disabled = box.checked? false : disable;
    }
}

// setTimeout is used so that if click comes from reset, the form is
// reset before listener runs
window.onload = function() {
  document.forms[0].onclick = function() {
    setTimeout(function(){toggleCheckboxes('fruits[]', 3)},10);
  }
}

</script>

<form>
  <input type="checkbox" name="fruits[]" value="apple">Apple<br>
  <input type="checkbox" name="fruits[]" value="orange">Orange<br>
  <input type="checkbox" name="fruits[]" value="pear">Pear<br>
  <input type="checkbox" name="fruits[]" value="cherry">Cherry<br>
  <input type="checkbox" name="fruits[]" value="plum">Plum<br>
  <input type="reset"><br>
</form>
于 2013-03-21T03:25:08.890 回答
0

您在输入之前发出脚本,因此脚本找不到要绑定的任何内容。包装<script>in的内容$(function () { ... });或将脚本移动到输入元素的下方。

于 2013-03-20T03:58:36.997 回答
0

把你的脚本文件 readt 函数..

>     > $(document).ready(function() {
>     > $('input[id="fruits"]').click(function(event) { if (this.checked &&
>     > $('input:checked').length > 3) { event.preventDefault();
>     > alert('You\'re not allowed to choose more than 3 boxes'); } }); });
于 2013-03-20T04:19:06.397 回答
0

看看这个,它可能会工作;)

限制复选框数量

于 2013-03-20T03:54:56.653 回答