使用PHP为单选,选择或复选框输入分配值 [英] Assigning a value to a radio, select or checkbox input with PHP
问题描述
我有一张注册表.当用户在输入无效的优惠券代码后提交表单时,页面将重新加载,我将再次显示该表单以及他们输入的所有数据.输入字段很容易,但是我想不出一种简单的方法来对广播,复选框和选择进行同样的操作.
例如,我有:
<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />
我的PHP变量$ gender包含男性".但是,如何选择带有男性"的收音机?
与我的选择和复选框相同的问题.
对于少数选项,您可以使用像这样的三元运算符.
<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 等.>
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.
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.
这篇关于使用PHP为单选,选择或复选框输入分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!