Bengau
Bengau

Reputation: 175

radio buttons with cookie

I try to set a cookie for 2 radio buttons and i don't know what i do wrong. I need to make it when a button is checked to remain checked even the page is refreshed. Can someone give me an advice with this? Thanks

This is my 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>

Upvotes: 1

Views: 2970

Answers (2)

Fluffeh
Fluffeh

Reputation: 33542

I don't quite follow your code, but the following should check the correct radio button for you:

<?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>

Upvotes: 2

Fry_95
Fry_95

Reputation: 241

This is checked="checked" for W3C not just 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>

Upvotes: 1

Related Questions