【问题标题】:How best to pre populate a radio button selection using php?如何最好地使用 php 预先填充单选按钮选择?
【发布时间】:2023-03-02 22:20:01
【问题描述】:

我正在处理申请表。

它将预先填充个人详细信息,我们已经有了他们的详细信息。基本上,我们会向他们发送一个指向他们的表单的链接,该链接已经填充了他们的详细信息,然后我们只需要求他们检查表单并在所有信息正确时点击提交。

我有以下内容可以预先填充简单的文本框:

<input type="text" name="forename" id="input-forename" value="<?php echo htmlspecialchars(@$_REQUEST['forename']);?>"/>    

<input type="text" name="birthdate" id="input-birthdate" value="<?php echo htmlspecialchars(@$_REQUEST['date_of_birth']);?>" />

等等

这一切都很好。

我在使用单选按钮时遇到了困难。

这个选择例如:

<label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" /></label>
<label for="input-title-mrs">Mrs: <input type="radio" name="title" id="input-title-mrs" value="Mrs" /></label>
<label for="input-title-miss">Miss: <input type="radio" name="title" id="input-title-miss" value="Miss" /></label>
<label for="input-title-ms">Ms: <input type="radio" name="title" id="input-title-ms" value="Ms" /></label>

是否有一种好方法可以使用 checked="" 属性和 php if 语句来预先检查正确的单选按钮?

大概是这样的:

<label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" checked="<?php if ( @$_REQUEST['forename'] == 'Mr' ) { echo 'checked'; }?>" /></label>

我希望这是有道理的,任何帮助或建议将不胜感激:)

【问题讨论】:

    标签: php forms if-statement radio-button


    【解决方案1】:
    <input type="radio" name="title" id="input-title-mr" value="Mr" <?php echo ($_REQUEST['title'] == 'Mr') ? 'checked="checked"' : ''; ?>  />
    

    【讨论】:

    • 我还有一些选择框。我可以对 selected="" 属性使用与此类似的方法吗?
    【解决方案2】:

    为什么不在链接中发送 get vars?比如www.thelink.com?title=Mr.

    然后使用:

    <label for="input-title-mr">Mr: <input type="radio" name="title" id="input-title-mr" value="Mr" <?php if($_GET['title'] == 'Mr') echo 'checked'; ?>" /></label>
    <label for="input-title-mrs">Mrs: <input type="radio" name="title" id="input-title-mrs" value="Mrs" <?php if($_GET['title'] == 'Mrs') echo 'checked'; ?>" /></label>
    

    等等……

    【讨论】:

    • 谢谢,这通常没问题,但恐怕在这种情况下是不可能的 :( Ravi 的回答虽然很有效!
    猜你喜欢
    • 2012-04-15
    • 2015-06-03
    • 2018-05-12
    • 1970-01-01
    • 2015-03-04
    • 2015-05-12
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    相关资源
    最近更新 更多