我尝试为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>
答案 0 :(得分: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>
答案 1 :(得分:1)
对于W3C,checked="checked"
不仅仅是checked
<?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>