繁体   English   中英

使用php遍历HTML表选中的复选框

[英]Looping through HTML table checked checkboxes using php

我有一个使用JavaScript的类似线程,但是我发现了一些问题和一些错误。 所以我改成了php

到目前为止,这是我的代码

if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $check) {
        //get the html data beside the checked checkboxes

    }
    }else{
        echo '<script language="javascript">';
        echo 'alert("Nothing checked")';
        echo '</script>'; 
    }

和我剥离的html代码

<tr>
                                <td><?php echo $r['Name'] ?></td>
                                <td><?php echo $r['Age'] ?></td>
                                <td><?php echo $r['Address'] ?></td>

                                <td><input name="check[]" type="checkbox"  ></td>
                            </tr>

我不会在选中复选框的同一行上获取数据。 请帮我。 谢谢

您必须遍历POST数据,并分配$ r [NAME] = VALUE

对于PHP代码:

    array $r;
    foreach($_POST as $post=>$value) {
        //get the html data beside the checked checkboxes
        $r[ $post] = $value;
        } 
    }
    }else{
        echo '<script language="javascript">';
        echo 'alert("Nothing checked")';
        echo '</script>'; 
    }

假设您引用的HTML部分是HTML的结果页:

<tr>
                                <td><?php echo $r['Name'] ?></td>
                                <td><?php echo $r['Age'] ?></td>
                                <td><?php echo $r['Address'] ?></td>

                            </tr>

首先,让我们添加一些数据:

<?php

$data = [
  '111' => [
    'Name' => 'John',
    'Age' => '25',
    'Address' => 'Baker street, 11'
  ],
  '222' => [
    'Name' => 'Mary',
    'Age' => '19',
    'Address' => 'Elm street, 14'
  ],
  '333' => [
    'Name' => 'Nick',
    'Age' => '23',
    'Address' => '64th stree, 2'
  ]
];

?>

输出所有数据项并设置以前发布的数据的检查:

<form method="POST">
<table>
  <?php foreach($data as $id => $item): ?>
  <tr>
    <td><?= $item['Name'] ?></td>
    <td><?= $item['Age'] ?></td>
    <td><?= $item['Address'] ?></td>
    <td><input name="check[]" type="checkbox" value="<?= $id; ?>"
      <?php if (isset($_POST['check']) && in_array($id, $_POST['check'])): ?>
      checked="checked"
      <?php endif; ?>/></td>
  </tr>
  <?php endforeach; ?>
</table>
<input type="submit" />
</form>
<?php if (empty($_POST['check'])): ?>
<script>alert("Nothing checked");</script>
<?php endif; ?>

提交表单后,您将重新加载带有正确标记的复选框的页面。

暂无
暂无

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

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