【问题标题】:Assigning a value to a radio, select or checkbox input with PHP使用 PHP 为单选、选择或复选框输入赋值
【发布时间】:2013-04-05 13:18:00
【问题描述】:

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

例如我有:

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

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

与我的选择和复选框相同的问题。

【问题讨论】:

  • &lt;?= ($gender=='male') ? 'selected' : ''; ?&gt;

标签: php forms input


【解决方案1】:

对于少数选项,您可以使用这样的三元运算符。

<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"' : '';?> />

不是最微妙的方式,但它会起作用。对于更复杂的情况,建议使用 DOM 解析器,如 DOMDocument 等。

【讨论】:

    【解决方案2】:
    //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']);
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多