繁体   English   中英

获取选中和未选中的复选框值

[英]Get checked and unchecked checkboxes value

这是我的脚本:

HTML代码:

<script>
function pickIt(pId){
    if(document.getElementById(pId).checked==true){
        document.getElementById(pId).checked=false;
    }else{
        document.getElementById(pId).checked = true;
    }
    submitForm();
    return true;
}
</script>
<img src="images/bagua-square.gif" border="0" usemap="#Map2" />
<map name="Map2" id="Map2">
    <area shape="rect" coords="201,14,284,100" onclick="pickIt(1);" />
    <area shape="rect" coords="202,104,284,190" onclick="pickIt(2);" />
    <area shape="rect" coords="202,195,284,283" onclick="pickIt(3);" />
</map>
<div style="display:none;">
    <input type="checkbox" id="1" name="box[]" />
    <input type="checkbox" id="2" name="box[]" />
    <input type="checkbox" id="3" name="box[]" />
</div>

PHP代码:

<?php
    print_r($_POST['box']);
?>

当我单击框ID 1 pickIt()函数时,将复选框1 启用 并且PHP显示数组(0 =>'on')

但我也想获取未选中的复选框值,以便php将显示array(0 =>'on',1 =>'off',2 =>'off')

实际上,我想获取所有复选框的状态为关,因为我正在mysql db中使用这些ID更新关的记录状态。 请指导。

如果选中复选框,复选框将发送其值,如果未选中,则根本不会发送。

你应该有:

<input type="checkbox" id="1" name="box[]" value="1" />
<input type="checkbox" id="2" name="box[]" value="2"  />
<input type="checkbox" id="3" name="box[]" value="3"  />

因此,值将是1、2和3,而不是on,on和on。 然后,您可以告诉我们检查了哪些内容,因为它们不会全部相同。

如果您确实希望数据结构为array(0=>'on', 1=>'off', 2=>'off')则可以执行以下操作:

$foo = array();
for ($i = 1; $i <= 3; $i++) {
    $foo[$i] = in_array($i, $_GET['box']) ? 'on' : 'off';
}

仅当选中复选框时,复选框才会发送到服务器(提交表单时),否则不提交

也改变

onclick="pickIt('1');" /

两种选择:

  1. 使每个复选框都具有隐藏字段,并在您取消选中该复选框时使用javascript将值设置为0或1。 然后忽略$_POST的“ on”值。
  2. PHP必须知道有多少个(和哪个)复选框,因此缺少的$_POST值是未选中的框。 您可以使用for循环执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM