0

我试图在提交表单后检查复选框的值(类似于验证),无论如何独立于选定的输入,我的代码无法确定用户选择了哪个输入。

例如: 选项 1 选项 2 选项 3

如果用户选择了选项 2,3,则代码选择选项 1,2。如果用户选择了选项 2,则代码选择选项 1。只有当用户选择选项 1 或选项 1、选项 2 或每个选项时,代码才能正常工作。

for ($y=0;$y<$n; $y++) {
    $caption_and_value = explode(":",$before_explode[$y]); 
    $caption = caption_and_value[0];
    $value = caption_and_value[1];
    $match .= '<input type="checkbox" name="'.$name_form[$y].'" value="'.$value.'"'; 
    if (isset($_POST[$name_form][$y])) {
        $match .= ' checked="checked"';
    } else {
        $match .= ''; 
    } 
    $match.='>'.$caption.'<br />';  
}

如果我做错了什么,请告诉我,我无法从几个小时内弄清楚这一点。谢谢!

4

2 回答 2

3

您应该使用一组复选框,更容易处理:

<input type="checkbox" name="boxes[]">
<input type="checkbox" name="boxes[]">
<input type="checkbox" name="boxes[]">

...然后在 PHP 中:

foreach($_POST['boxes'] as $key => $value) {
    echo $key . ': ' . $value;
}
于 2013-10-22T23:13:31.290 回答
0

我有这个。这是表格:

<form method='POST' action = 'process.php'>
<?php 
for ($i=1;$i<=3;$i++){
echo "<input type='checkbox' name='box[]' value='$i'>$i<br>";
}
?>
<input type='submit' value='send'>
</form>

它是 php :

    <?php 
    $input_value = $_POST['box'];
    $i = 0;
    $choice1 = NULL;
    $choice2 = NULL;
    $choice3 = NULL;
    foreach ($input_value as $value){
    if ($value == "1"){
    $choice1 = "active";
    }
    if ($value == "2"){
    $choice2 = "active";
    }
    if ($value == "3"){
    $choice3 = "active";
    }
    }
//choice checker script block
    if (!isset($choice1) and !isset($choice2) and !isset($choice3)){
    echo "You didn't choose anything!";
    }
    if ($choice1 == "active" and $choice2 == NULL and $choice3 == NULL){
    echo "You only chose 1";
    }
    if ($choice2 == "active" and $choice1 == NULL and $choice3 == NULL){
    echo "You only chose 2";
    }
    if ($choice3 == "active" and $choice2 == NULL and $choice1 == NULL){
    echo "You only chose 3";
    }
    if ($choice1 == "active" and $choice2 == "active" and $choice3 == NULL){
    echo "You chose 1 and 2";
    }
    if ($choice1 == "active" and $choice3 == "active" and $choice2 == NULL){
    echo "You chose 1 and 3";
    }
    if ($choice3 == "active" and $choice2 == "active" and $choice1 == NULL){
    echo "You chose 2 and 3";
    }
    if ($choice1 == "active" and $choice2 == "active" and $choice3 == "active"){
    echo "You chose all of the choice!";
    }
// end of choice checker script blok
    ?>

可能有点混乱和大量的代码。:D
但是,如果你想检查用户选择的选项,我已经在上面创建了“选择检查脚本”。
实际上,您可以更改或替换if($choice == 'active')if(isset($choice)),但它会返回相同的值。试试看!你会知道如何定制它。
我认为这就是你要找的。

于 2013-10-23T02:54:35.663 回答