1

我尝试为 2 个单选按钮设置一个 cookie,但我不知道我做错了什么。即使页面刷新,我也需要在检查按钮时保持选中状态。有人可以给我一个建议吗?谢谢

这是我的 test.php

<?php 
    if(isset($_POST['radio1'])) {
      setcookie('radio1', true, 600, '/');
      setcookie('radio2', false, 600, '/');
    } else if(isset($_POST['radio2'])) {
      setcookie('radio2', true, 600, '/');
      setcookie('radio1', false, 600, '/');
    }
    ?>

    <form method="POST" action="test.php">
      <div id="radio">
        <input type="radio" id="radio1" name="radio" checked="checked" />
        <label for="radio1">Choice 1</label>
        <input type="radio" id="radio2" name="radio" />
        <label for="radio2">Choice 2</label>
      </div>
    </form>
4

2 回答 2

2

我不太遵循您的代码,但以下应该为您检查正确的单选按钮:

<?php 
if(isset($_POST['radio']) && $_POST['radio']=='val1') {
  setcookie('radio1', true, 600, '/');
  $radio1=' checked ';
  $radio2='';
  setcookie('radio2', false, 600, '/');
} else if(isset($_POST['radio'])&& $_POST['radio']=='val2') {
  setcookie('radio2', true, 600, '/');
  $radio1='';
  $radio2=' checked ';
  setcookie('radio1', false, 600, '/');
}
?>

<form method="POST" action="test.php">
  <div id="radio">
<input type="radio" id="radio1" name="radio" <?php echo $radio1;?> value="val1" />
<label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" <?php echo $radio2;?> value="val2" />
<label for="radio2">Choice 2</label>
<input type="submit">
  </div>
</form>
于 2012-09-27T11:45:34.180 回答
1

checked="checked"不仅适用于 W3Cchecked

<?php 
    if (isset($_POST['radio']) && $_POST['radio'] == "radio1") {
        setcookie('radio1', "true", 600, '/');
        setcookie('radio2', "false", 600, '/');
        $radio1 = ' checked="checked"';
        $radio2 = '';
    } else if(isset($_POST['radio']) && $_POST['radio'] == "radio2") {
        setcookie('radio1', "false", 600, '/');
        setcookie('radio2', "true", 600, '/');
        $radio1 = '';
        $radio2 = ' checked="checked"';
    }

    if (isset($_COOKIE['radio1']) && $_COOKIE['radio1'] == "true") {
        $radio1 = ' checked="checked"';
        $radio2 = '';
    } else if (isset($_COOKIE['radio2']) && $_COOKIE['radio2'] == "true") {
        $radio1 = '';
        $radio2 = ' checked="checked"';
    }
    ?>

    <form method="POST" action="test.php">
        <div id="radio">
            <input type="radio" id="radio1" name="radio" value="radio1" <?= $radio1; ?> />
            <label for="radio1">Choice 1</label>
            <input type="radio" id="radio2" name="radio" value="radio2" <?= $radio2; ?> />
            <label for="radio2">Choice 2</label>
        </div>
    </form>
于 2012-09-27T11:49:29.527 回答