0

我想知道如何同时获取由 ID 分配给它的复选框的值。

这是我的简短代码:

<table class="data" cellpadding="0" cellspacing="0">
<?php
$select=mysql_query("select * from products_list ORDER BY id ASC");
while($row=mysql_fetch_array($select)){

$class = ' class="new_arrival" ';

echo "<tr>
<td>".$row['id']."</td>
<input type='hidden' name='product_id' value='".$row['id']."' />
<input type='checkbox' name='product_new' checked='checked' onclick='document.product_listing.submit();' /></td></tr>";
?>
</table>

if (isset($_POST['product_new'])) {

$id = $_POST['product_id'];

echo ("<script language='JavaScript'>
    window.alert('".$id."')
    </script>");
}

我不断得到的 ID 结果是数据库中的最新记录,但复选框的值工作正常。

我试过这个:

<input type='checkbox' name='product_new[".$row['id']."]' checked='checked' onclick='document.product_listing.submit();' />

foreach($_POST['product_category'] as $id => $value)

使用 foreach 循环,它确实以某种方式工作,但无论是选中还是取消选中,它都会遍历这些复选框。

希望你们理解,被困在这两天了。我的目的是单击复选框,无论是选中还是取消选中,它都会根据 mysql show result 分配的 ID 更新数据库。

任何帮助都感激不尽。谢谢!!

4

3 回答 3

1

我不太明白你到底想用复选框做什么,但这里有几件事可以帮助你做任何你想做的事情:

  1. 如果未选中,HTML 表单不会提交复选框的值,例如,如果您有一个复选框,并且您提交未选中的表单,如果您尝试访问 chkbox1,您将获得 null

  2. 如果您想知道是否选中了单击的复选框,您可以通过让每个 onclick 传递 id 的值来做到这一点,例如

<input type='checkbox' name='product_new[".$row['id']."]' checked='checked' onclick='setValueAndSubmit(<?=$row[id]?>)' />

并在js中编写检查复选框的选中属性并进行相应处理的函数

或者

如果您希望查看提交时的所有复选框值,那么您可以简单地遍历复选框组,您只会找到已选中的复选框的复选框名称,未选中的复选框将不会被提交。

编辑:只需在每个复选框后删除 onclick 并放置一个提交按钮,一旦表单提交,您将获得选中复选框的名称和值,因此设置这些复选框,并取消设置所有其他复选框。

于 2012-07-27T10:30:06.957 回答
0

只需将 id 放在value=复选框的属性中即可。

要生成 HTML:

<table class="data" cellpadding="0" cellspacing="0">
<?php

  $query = "
    SELECT *
    FROM products_list
    ORDER BY id ASC
  ";
  $result = mysql_query($query);

  // What if the query fails? Handle error here!

  while ($row = mysql_fetch_ssoc($result)) {

    // ...

    echo "
    <tr>
      <td>".htmlspecialchars($row['id'])."</td>
      <td><!-- I'm guessing this open td tag was missing and should be added -->
        <input type='checkbox' name='product_new[]' checked='checked' value='".htmlspecialchars($row['id'])."' />
        <!-- You don't want the onclick for the checkbox to submit the form, or you will only ever get one result -->
      </td>
    </tr>";

    // ...

  }

?>
</table>

提交表单时:

if (isset($_POST['product_new'])) {
  foreach ($_POST['product_new'] as $id) {
    // Do stuff with $id here
  }
}
于 2012-07-27T10:39:23.480 回答
0

如果我正确理解了这个问题......

发生这种情况是因为有多个名为 product_id 的输入,因此按名称引用会导致一个被采用,但不是您想要的那个。

因此,解决方法是将单个字段 product_id 添加到循环外部的表单中,并在复选框的 onClick 中更改该值。

示例点击:

<input type='checkbox' name='product_new' checked='checked' onclick='document.product_listing['product_id'] = ".$row['id'].";document.product_listing.submit();' /></td></tr>";`

像这样的东西应该可以工作。

于 2012-07-27T10:32:47.900 回答