我想阻止用户选择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();
?>
答案 0 :(得分:0)
看看这个,它可能有用;)
答案 1 :(得分:0)
您在输入之前发出脚本,因此脚本找不到要绑定的内容。在<script>
中包含$(function () { ... });
的内容,或将脚本移到下面输入元素。
答案 2 :(得分:0)
将您的脚本文档准备好功能..
> > $(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'); } }); });
答案 3 :(得分: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>