【问题标题】:I need to keep a table of check boxs checked我需要检查复选框表
【发布时间】:2013-07-11 13:42:28
【问题描述】:

我创建了一个二维数组并结合嵌入式循环创建了一个复选框表,如何在用户单击提交按钮后保持复选框处于选中状态?我怀疑会话变量是必要的,但我不确定如何在这段代码中实现它。这是一个类项目,我们应该在其中创建一个战舰游戏。课堂上没有人能够帮助我解决这个问题。请记住,这是一个介绍性课程,所以当您提交答案时不要指望我知道很多。这是创建板的一些代码。如果您需要更多信息,请告诉我。

function createBoard(){
    //building the arrays
$column1 = array(
'a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'
);
$column2 = array(
'b1','b2','b3','b4','b5','b6','b7','b8','b9','b10'
);
$column3 = array(
'c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'
);
$column4 = array(
'd1','d2','d3','d4','d5','d6','d7','d8','d9','d10'
);
$column5 = array(
'e1','e2','e3','e4','e5','e6','e7','e8','e9','e10'
);
$column6 = array(
'f1','f2','f3','f4','f5','f6','f7','f8','f9','f10'
);
$column7 = array(
'g1','g2','g3','g4','g5','g6','g7','g8','g9','g10'
);
$column8 = array(
'h1','h2','h3','h4','h5','h6','h7','h8','h9','h10'
);
$column9 = array(
'i1','i2','i3','i4','i5','i6','i7','i8','i9','i10'
);
$column10 = array(
'j1','j2','j3','j4','j5','j6','j7','j8','j9','j10'
);
//build the master array
$row = array(
"a"=>$column1,
"b"=>$column2,
"c"=>$column3,
"d"=>$column4,
"e"=>$column5,
"f"=>$column6,
"g"=>$column7,
"h"=>$column8,
"i"=>$column9,
"j"=>$column10
);
    print<<<HERE
    <form method = "post"
        action = "">
    <table border = "1">

    HERE;
    for ($i="a";$i<="j";$i++){
    print "<tr>";
    foreach ($row["$i"] as $chkRow){

    print "<td><input type = 'checkbox' name = '$chkRow' value = '$chkRow'/>$chkRow</td>\n";
    }//end foreach
    print"</tr>\n";
    } //end for loop

    print "</table>";
    print "<button type = 'submit'>Fire!</button></form>";

    } //end function

【问题讨论】:

  • 您知道根据 POSTed 值检查了哪些项目吧?所以现在你只需要根据完整的值数组评估这些发布的值,对于那些被检查的值,在元素中输出checked="checked"

标签: php checkbox html-table session-variables


【解决方案1】:

没有经过测试,在我的脑海中,但应该是构建复选框网格并在网格中添加/删除更多内容时保持选中状态的基础。

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['shots'] = $_POST['shots'];
}

echo '<form method="post"><table>';
for($i = 1; $i < 10; $i++) {
   echo '<tr>';
   for ($j = 'a'; $j <= 'j'; $j++) {  // this works, but you shouldn't not be doing "math" on characters
      $has_shot = isset($_SESSION['shots'][$i][$j]) ? ' checked="checked"' : '';
      echo "<td><input type='checkbox' name='shots[$i][$j]'$has_shot /></td>";
   }
   echo '</tr>'
}
echo '</table><input type="submit"></form>';

【讨论】:

  • 我刚刚更新了我的问题以包含数组。这应该可以解释为什么我在 for 循环中使用 'a' 到 'j' 而不是 1-10。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 2015-10-09
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多