【问题标题】:Wordpress - How to echo radio button in PHP using html .=?Wordpress - 如何使用 html .= 在 PHP 中回显单选按钮?
【发布时间】:2021-01-19 18:53:49
【问题描述】:

我有一个包含单选按钮的表单,其中结果存储在数据库中(是或否)。我正在尝试从存储的数据库值中设置选定的单选按钮,但在遵循几个推荐的解决方案后无法弄清楚。 $existing_military_status 的回声返回“否”。因为我使用的是 Wordpress,所以我必须从函数中返回 html,因此我使用 html .= nomenclature。

我得到的结果是未选中“否”单选按钮。请注意,我还没有提交表单,这将通过 Ajax 调用完成。

在确认单选按钮应该被选中后,如何将其设置为“选中”?

非常感谢任何帮助。

相关PHP:

$existing_military_status = ( get_user_meta( $user_id, 'user-military-status', true ) ) ? get_user_meta( $user_id, 'user-military-status', true ) : '';

$html .= "<input id='yes' type='radio' name='user-military-status' value='Yes' if ($existing_military_status === 'Yes') echo 'checked=\"checked\"'>\n";
$html .= "<label for='yes'><span class='radio'>Yes</span></label>\n";
$html .= "</div>\n";
$html .= "<div id='military-no-container' style='float: left;' class='radio-container'>\n";
$html .= "<input id='no' type='radio' name='user-military-status' value='No' if ($existing_military_status === 'No') echo 'checked=\"checked\"'>\n";
$html .= "<label for='no'><span class='radio'>No</span></label>\n";
$html .= "</div>\n";

【问题讨论】:

    标签: php html wordpress radio-button


    【解决方案1】:

    PHP 解释器无法区分字符串和 PHP 代码。我建议在字符串之外创建变量和条件语句。

    $isYes = ($existing_military_status === 'Yes') ? 'checked' : '';
    $isNo  = ($existing_military_status === 'No') ? 'checked' : '';
    
    $html = "<input id='yes' type='radio' name='user-military-status' value='Yes' " . $isYes . ">\n";
    $html .= "<input id='no' type='radio' name='user-military-status' value='No' " . $isNo . ">\n";
    

    【讨论】:

    • 我可以将 PHP 包含在标签中,以便解释器区分 PHP 代码吗?我实际上尝试过,但无法让它工作。只是好奇,因为它会简化我的代码。我有很多完整形式的单选按钮。
    • 是的,你可以附上它。请在此处查看答案stackoverflow.com/questions/13089747/…
    • 我没有反馈说这很好用。谢谢!
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多