保持单选按钮值并设置默认选中

时间:2014-04-22 22:11:49

标签: php forms validation radio-button

我有一个带有单选按钮组的表单。我想将'checked'设置为默认的第二个单选按钮,如果用户点击第一个单选按钮,也会在提交表单后保留该值。

请注意,我使用<span class="custom-radiobutton"></span>来设置无线电按钮的样式,其z-index低于真实<input type="radio" opacity:0

这是我的代码片段:

<div class="group-wrapper">
  <div class="radiobutton-wrapper boolean">
    <span class="custom-radiobutton"></span>
    <input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if ((isset($_POST['hosting'])) && ((isset($_POST['hosting'])) == 1)) {echo 'checked="checked"';}; ?> /> 
    <label for="hosting-1">Sí</span>
  </div>
  <div class="radiobutton-wrapper boolean">
    <span class="custom-radiobutton"></span>
    <input type="radio" id="hosting-2" name="hosting[]" value="0" class="w100" <?php if ((!isset($_POST['hosting'])) || ((isset($_POST['hosting'])) == 0)) {echo 'checked="checked"';}; ?> /> 
    <label for="hosting-2">No</label>
  </div>
</div>

其他信息:

  • 我正在使用HTML5。
  • 我正在使用PHP验证表单(我想保留它,即使我知道也许是更好的jQuery + PHP验证)。
  • 我注意到我需要两次点击才能选择第一个单选按钮。这只发生在原始状态。在此之后,按预期方式单击即可。

我花了很多时间试图弄清楚什么是错的,所以任何帮助都会非常感激。 欢呼声,

2 个答案:

答案 0 :(得分:1)

<input type="radio" id="hosting-1" name="hosting[]" class="w100"  checked="checked" /> 1

在您的代码中尝试此操作。

例如:

<tr>
    <td><br><b>Reservation Handling :  <span style="color:#FF0000">* &nbsp;&nbsp;</span></td>
    <td><br><input type="radio" name="reservation" value="Delighted" required> Delighted<br></input></td>
</tr>
<tr>
    <td> </td>
    <td><input type="radio" name="reservation" checked="checked" value="Satisfied"> Satisfied</input></td>
</tr>
<tr>
    <td> </td>
    <td><input type="radio" name="reservation" value="Dissatisfied"> Dissatisfied</input></td>
</tr>
<tr>
    <td> </td>
    <td><input type="radio" name="reservation" value="N/A"> N/A</input></td>
</tr>       

答案 1 :(得分:0)

您的逻辑中有错误。你正在使用isset两次。

<input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if ((isset($_POST['hosting'])) && ((isset($_POST['hosting'])) == 1)) {echo 'checked="checked"';}; ?> /> 

你基本上是说isset等于1,如果$ _POST ['hosting']有一个值,在你的情况下总是如此。

你应该这样做

<input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if (isset($_POST['hosting']) && $_POST['hosting'] == 1) {echo 'checked="checked"';} ?> /> 
相关问题