0

我有一个登记表。当用户在输入无效的优惠券代码后提交表单时,页面会重新加载,我会再次显示表单以及他们输入的所有数据。输入字段很容易,但我想不出一种简单的方法来处理单选、复选框和选择。

例如我有:

<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />

我的 PHP 变量 $gender 包含“男性”。但是如何选择带有“男性”的收音机?

我的选择和复选框也有同样的问题。

4

2 回答 2

1

For a small number of options you could use a ternary operator like this.

<input type="radio" name="gender" value="male" <?php echo ($gender == 'male') : 'selected="selected"' : '';?> />
<input type="radio" name="gender" value="female" <?php echo ($gender == 'female') : 'selected="selected"' : '';?> />

Not the most subtle way but it will work. For more complicated situations its advisable to use a DOM parser like DOMDocument etc.

于 2013-04-12T21:28:29.907 回答
0
//retrive gender and checkbox value in edit form
$gender=$row['gender'];
$chkhobby=$row['chkhobby'];
<tr>
                    <th>GENDER</th>
                    <td>
                            Male<input type="radio" name="gender" value="1" <?php echo ($gender== '1') ?  "checked" : "" ;  ?>/>
                            Female<input type="radio" name="gender" value="0" <?php echo ($gender== '0') ?  "checked" : "" ;  ?>/>

                    </td>
                </tr>
                <tr>
                    <th>Hobbies</th>
                    <td>
                        <pre><?php //print_r($row);

                            $hby = @explode(",",$row['chkhobby']);
                            //print_r($hby);
                        ?></pre>
                        read<input id="check_1" type="checkbox" name="chkhobby[]" value="read" <?php if(in_array("read",$hby)){?> checked="checked"<?php }?>>
                        write<input id="check_2" type="checkbox" name="chkhobby[]" value="write" <?php if(in_array("write",$hby)){?> checked="checked"<?php }?>>
                        play<input id="check_4" type="checkbox" name="chkhobby[]" value="play" <?php if(in_array("play",$hby)){?> checked="checked"<?php }?>>


                    </td>
</tr>
//update
$gender=$_POST['gender'];
        $chkhobby = implode(',', $_POST['chkhobby']);
于 2016-08-11T08:57:21.377 回答