double0201 2011-10-20 11:54
浏览 63
已采纳

如何验证多重复选框状态?

I am using position absolute's validation engine for my form. I would like to check whether at least one checkbox from group is selected. In examples it is done by setting the same name attribute for group of checkboxes. I cannot name checkboxes with the same name, because I am saving their state in database with following code:

$values = array(
    'checkbox1'         => null,
    'checkbox2'         => null
);

foreach (array_intersect_key($_POST, $values) as $key => $value) {
    $values[$key] = mysql_real_escape_string($value);
}

$query_add_candidate=sprintf("INSERT INTO dbase (checkbox1, checkbox2)    VALUES    ('$values[checkbox1]', '$dates[checkbox2]')"

Now checkbox1 and checkbox2 are validated individually, beacuse they have different names. How can I check if selected is at least one of them?

Here is my HTML code:

<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox1" id="maxcheck1" value="1"/> Text1
<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox2" id="maxcheck2" value="2"/> Text2
  • 写回答

3条回答 默认 最新

  • douzuizhuo0587 2011-10-20 11:59
    关注

    on php ,

    if(!$_POST['checkbox1'] && !$_POST['checkbox2']){
        echo 'Error check at least one';
    }
    

    but what you really want is an array, HTML,

    <input type="checkbox" value="ch1" name="check[]" /> 
    <input type="checkbox" value="ch2" name="check[]" />
    

    php

    <?php 
    if(empty($_POST['check'])){
     echo 'Error: hey, check at least one will you!?'; 
    }
    
    ?>
    

    so this way you don't have to check all of them one by one, especially if you have loads of them on the same page.

    NOTICE: You should also know, if checkbox is not ticked it will also not be set on the php $_POST superglobal, otherwise if it is ticked, it will show whatever the value="..." holds,

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line