如何在一个表单中只允许2个选择复选框

How to allow only 2 selection checkbox in a form with?

本文关键字:2个 复选框 选择 表单 一个      更新时间:2023-09-26

我想在我的网站上放一个表格,给3个奖品。每个成员只能在列表中选择2个他们希望赢得的项目。

我已经创建了表单,用JavaScript它工作得很好,但它是客户端,不能被信任。

实现这样的事情并确保每个用户只能选择2个项目的最佳方法是什么?使用PHP最好的方法是什么?

感谢您的帮助。

jQuery是老大,看看这里

http://gravitywiz.com/2012/06/11/limiting-how-many-checkboxes-can-be-checked/

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Price 1<input value="price1" type="checkbox" name="price[]">
Price 2<input value="price2" type="checkbox" value="price[]">
Price 3<input value="price3" type="checkbox" value="price[]">
<input type="submit" name="send" value="Send" />
</form>

然后检查数组的大小$_POST['price']:

<? 
   if(isset($_POST['send'])) {
       if(sizeof($_POST['price']) == 2) {
           //here you go
       } else { 
          echo "error, pick exactly two prices!";
       } 
   }
?>

为什么不用单选按钮呢?

<form method="post">
     Price 1 <input type="radio" value="price 1" />
     Price 2 <input type="radio" value="price 2" />
     Price 3 <input type="radio" value="price 3" />
</form>

如果您想允许多个奖品,只需切换到复选框

<form method="post">
     Price 1 <input type="checkbox" name="price[]" value="price 1" />
     Price 2 <input type="checkbox" name="price[]" value="price 2" />
     Price 3 <input type="checkbox" name="price[]" value="price 3" />
</form>