2011-08-16 90 views
0

当我将带有复选框的html表单传递给php页面时,当我检索它们时,我检查所有框的值为true,未检查框的值为false。我只需要获得价值。获取php中的复选框值

<?php 
$contact=$_POST['contact']; 

foreach ($contact as $conid){ 
    echo $conid 
} 
?> 
+1

发表您的HTML也请 – calumbrodie

+1

http://stackoverflow.com/questions/2268887/php-checkbox -input http://stackoverflow.com/questions/6291370/how-to-get-value-of-checked-checkbox-in-php – blottedscience

+0

复选框总是“TRUE”或“FALSE”,这就是它们的重点 - 什么你想要的价值,究竟是什么? – DaveRandom

回答

4

一种可能的方法是设置名称那样:

<input type='checkbox' name='box[1]'> 
<input type='checkbox' name='box[2]'> 
<input type='checkbox' name='box[3]'> 

这样,您就可以访问他们在PHP与

foreach ($_POST['box'] as $id=>$checked){ 
    if ($checked =='on') 
     //process your id 
} 

第二种方法更干净,我想。设定值对复选框属性:

<input type='checkbox' name='box[]' value='1'> 
<input type='checkbox' name='box[]' value='2'> 
<input type='checkbox' name='box[]' value='3'> 

有了这个,你就只会收到检查的值:

foreach ($_POST['box'] as $id){ 
     //process your id 
} 
+3

你的第一种方法是不正确的。 '$ checked =='true''将(总是)返回false,因为例如Chromium在复选框被选中时发送'on'。如果您为复选框设置了值,则会发送该值。使用这些值和第二种方法,不仅可以发送ID,还可以发送相关值。 (例如'') – feeela

+0

右边,FF也发送'on'。我的错误:)编辑 – J0HN

+0

你真的不应该依赖字符串,这是发送,如果没有给出的价值。最好只检查一下,发送哪些名称。 – feeela