使用php限制所需的复选框数量

时间:2015-11-25 15:10:32

标签: php

我一直试图找到解决方案3天。希望有人可以提供帮助。复选框需要将用户限制为2个或更多选择。我知道如何使用javascript,但需要使用PHP。这是可能的,如果是的话,怎么样?

            <label><input type="checkbox" value="Lemon" name='filling[]'  />Lemon</label></br>
        <label><input type="checkbox" value="Custard" name='filling[]'  />Custard</label></br>
        <label><input type="checkbox" value="Fudge" name='filling[]'  />Fudge</label></br>
        <label><input type="checkbox" value="Mocha" name='filling[]'  />Mocha</label></br>
        <label><input type="checkbox" value="Raspberry" name='filling[]'  />Raspberry</label></br>
        <label><input type="checkbox" value="Pineapple" name='filling[]'  />Pineapple</label>

3 个答案:

答案 0 :(得分:0)

您可以通过计算选择次数

来完成此操作
if(count($_POST['filling']) < 2){
    // throw error
}

答案 1 :(得分:0)

我假设您正在尝试通过PHP处理表单的提交,并希望用户至少选择2个复选框。提交表单时,复选框仅在检查时发送到服务器。在您的设置中,您使用数组作为名称。只需检查阵列的大小是否至少为2。

$checkboxes = $_POST['filling'];

if( count($checkboxes) < 2 ) {
    die("You must select at least 2 checkboxes.");
}

显然,你可以做更多的事情,但你得到了要点。

答案 2 :(得分:0)

这两个回复给了我一个良好的开端。得到它使用以下PHP。

if(empty($_POST['filling']) || count($_POST['filling']) < 2)
{
show_error("Please select at least two fillings");
}
$filling = check_input(implode("," , $_POST['filling']));