开发者

HTML/PHP - I need to create a 10 by 10 grid with a 100 boxes, each needs to be selectable

I've created the grid using tables, but can't seem to figure out how to allow the user to select a specific box in the grid. (i.e. user selects 3 boxes, each having xy coordinates, which I would need to store in a database)

Maybe I should not be using tables and instead using divs?

Any help would be appreciated.

NOTE: I'm a newbie to PHP so please don't assume I know 开发者_如何学Cmuch :)


It doesn't look that the layout matters for your problem, whether it's table or div based. If I understand correctly you need to get coordinates like 3-2 in case the user clicks on the box located on the 3rd case of the 2nd column.

To do that you just need to use an array of array for your variables.

<input type="checkbox" name="boxes[<?php echo $i;?>][<?php echo $j;?>]" value="1" />

Then you increment i and j variables properly to get boxes names from boxes[0][0] to boxes[9][9].

Finally, on the server side when the user submits the form, you can check values like that:

$boxes = $_POST['boxes'];
for (int i=0; i<9; i++) {
  for (int j=0; j<9; j++) {
    if (isset($boxes[$i][$j])) {
      // here you have your coordinates for a selected box
    }
  }
}


I'd steer clear of tables in general.

If you made a grid of buttons, in a form, you could:

  • Edit their style to look like cells
  • Submit the form when the user clicks
  • Use the POST data to highlight the one that was clicked


Most depends on what you have to do, but this simple example should do exactly what you need. Consider to use a JS framework.

<style>
td{empty-cells: show;}
</style>
<script>
 function cellSelected(this,i,q)
 {
    alert("Cell ("+i+","+q+")");
 }
</script>
<?php
echo '<table>';
for($i=0;$i<10;$i++)
{
  echo '<tr>';
  for($q=0;$q<10;$q++)
  {
    echo '<td onClick="cellSelected(this,'.$i.','.$q.')"></td>';
  }
  echo '</tr>';
}
echo '</table>';
?>


Thanks everyone.

Here's what I ended up doing

  • assigned id's to each cell/td [00] - [99]
  • onclick called a function that stored the cell's id in a hidden input
  • record the values in the hidden input upon form submission

Sort of combined two solutions from above. Hopefully I can contribute to these discussions as I learn a bit more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜