单选按钮需要保持选中状态

Radio buttons need to stay checked

我需要制作两个在提交后保持选中状态的单选按钮。我正在 Joomla 文章中制作这个。我安装了 DirectPHP,所以我可以使用 php 和 javascript。我到目前为止的代码:

<form>
<input name="button" type="radio" value="1" id="button1" /> 
<input name="button" type="radio" value="2" id="button2" />
<input type="submit" value="submit" />
</form>
<form>
<input name="button" type="radio" value="1" id="button1"<?php if ($_REQUEST['button1'] === 1) echo " checked"; ?>/> 
<input name="button" type="radio" value="2" id="button2"<?php if ($_REQUEST['button2'] === 1) echo " checked"; ?>/>
<input type="submit" value="submit" />
</form>

仅供参考:
如果省略该方法,则表单默认为 GET。

  • <form>等同于做<form method="get">

如果您的 PHP 使用 POST 数组,那么您将需要指定方法并且没有在您的问题中提供任何额外的代码。

即:<form method="post">

像这样检查输入标签的内部:

<form>
<input name="button" type="radio" value="1" id="button1" <?php if($_GET["button"]==1 ){ echo "checked"; }?> /> 
<input name="button" type="radio" value="2" id="button2" <?php if($_GET["button"]==2 ){ echo "checked"; }?> />
<input type="submit" value="submit" />
</form>

根据需要更改名称和方法。

  • 旁注:如果您的 PHP 使用 POST 数组并指定 "post" 方法,请将 GET 更改为 POST

<form>
  <input name="button1" type="radio" value="1" id="button1" <?php if ($_REQUEST[ 'button1']===1 ) echo "checked"; ?>/>
  <input name="button2" type="radio" value="2" id="button2" <?php if ($_REQUEST[ 'button2']===2 ) echo "checked"; ?>/>
  <input type="submit" value="submit" />
</form>