Assigning a value to a radio, select or checkbox i

2019-08-20 07:57发布

问题:

I've got a registration form. When users submit the form after entering an invalid coupon code, the page reloads and I show the form again with all the data they entered. It's easy with input fields but I can't think of a simple way to do the same with radio, checkboxes and selects.

For example I have :

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

I have my PHP variable $gender that contains 'male'. But how to have the radio with 'male' selected?

Same question with my selects and checkboxes.

回答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.



回答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']);


标签: php forms input