PHP在选中/取消选中时获取复选框值

时间:2014-05-20 12:01:35

标签: php mysql

<?php

// $groups is fetch_array from mysql
foreach($groups as $group) {
    if ($group['delete_user'] === 'Y') {
        $checked = "checked=\"checked\";
    }
    else {
        $checked = '';
    }
?>
    <input type = "checkbox" name="delete_user[<?php echo $group['id']; ?>]" <?php echo $checked; ?>>
<?php

}
?>

将输出:

<form action="test.php" method="post">
    <input type="checkbox" name="delete_user[1]">
    <input type="checkbox" name="delete_user[2]">
    <input type="checkbox" name="delete_user[3]">
    <input type="checkbox" name="delete_user[4]" checked="checked">
    <input type="submit" name="save_action" value="Save">
</form>

当我按需检查输入时,这将处理输入。

<?php
if(isset($_POST['save_action']) {
    if (empty($_POST['delete_user'])) {
        $_POST['delete_user'] = array();
    }
    foreach($_POST['delete_user'] as $del) {
        is_checked($del); //@todo 
    }
}
?>

我正在寻找检查是否选中复选框并返回正确值(Y或N)的方法。在这一点上,我为此目的声明了is_checked()函数。

3 个答案:

答案 0 :(得分:0)

我会这样做:

<form action="test.php" method="post">
    <input type="checkbox" name="delete_user[]" value="1">
    <input type="checkbox" name="delete_user[]" value="2">
    <input type="checkbox" name="delete_user[]" value="3">
    <input type="checkbox" name="delete_user[]" value="4" checked="checked">
    <input type="submit" name="save_action" value="Save">
</form>

现在在PHP中,您可以循环遍历$ _POST ['delete_user'],它将包含所选项的值。

foreach($_POST['delete_user'] as $item)
{
   // code to delete $item
}

答案 1 :(得分:0)

正如已经提到的评论一样,只会设置选中的复选框 因此,您必须将索引作为ID或为每个输入元素添加一个val。 后者可能更清洁(在我看来)

<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
    if ($group['delete_user'] === 'Y') {
        $checked = "checked=\"checked\";
    }
    else {
        $checked = '';
    }
?>
    <input type = "checkbox" name="delete_user[]" <?php echo $checked; ?> value="<?php echo $group['id'];?>">
<?php
}
?>

与输入有关的代码:

<?php
if(isset($_POST['save_action']) {
    if (empty($_POST['delete_user'])) {
        $_POST['delete_user'] = array();
    }
    foreach($_POST['delete_user'] as $del) {
        // do something with $del - the id
    }
}
?>

答案 2 :(得分:0)

使用复选框名称作为数组,然后将id作为值。请参阅以下代码。

<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
 if ($group['delete_user'] === 'Y') {
    $checked = "checked=\"checked\";
 }
 else {
    $checked = '';
 }
?>
 <input type = "checkbox" name="delete_user[]" value="<?php echo $group['id']; ?>" <?php echo $checked; ?>>
<?php

}
?>

然后在操作页面上放置此代码

<?php
      foreach($_POST['delete_user'] as $del) {
      is_checked($del); //@todo 
   }
}
?>

这样可以正常工作。