Hi,

I have a php page called: radio_page.php, it contains two radio buttons. First radio button is checked as default when loading the page. I need when clicking on second radio button to refresh the page and keep selection on second radio button, I am trying that as below, but it does not work. After refreshing the page the selection returns to the first radio button. Please advise. Thanks.

////////////radio_page///////
echo "<input type=radio id=rad1 checked=checked name=rad value=radio1 onclick=SelectRadio('rad1')> ";

echo "<input type=radio id=rad2 name = rad value=radio2 onclick=SelectRadio('rad2')> Time";


//////////javascript//////////
function SelectRadio(rad){
var selected_radio = document.getElementById(rad).value; 
if(rad == 'rad2'){
     window.location.href = 'radio_page.php';
     document.getElementById(rad).checked = 'checked';

}
else{
     window.location.href = 'radio_page.php';
     document.getElementById(rad).checked = 'checked';

}

}

Dani AI

Generated

What resets your selection is the full page reload: the DOM is rebuilt, so any client-side changes are lost. If you do use JavaScript to set a radio, prefer the boolean property (el.checked = true) rather than assigning the string "checked". For a robust solution that survives refreshes, persist the choice and render the checked state on the server.

Here is a POST + session pattern that avoids query strings and works even after a redirect:

<?php
// radio_page.php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['choice'])) {
    $_SESSION['choice'] = $_POST['choice'];
    header('Location: radio_page.php'); // PRG pattern
    exit;
}
$selected = $_SESSION['choice'] ?? 'radio1';
?>
<form method="post">
  <label>
    <input type="radio" name="choice" value="radio1" <?php echo $selected === 'radio1' ? 'checked' : ''; ?> onchange="this.form.submit()">
    Option 1
  </label>
  <label>
    <input type="radio" name="choice" value="radio2" <?php echo $selected === 'radio2' ? 'checked' : ''; ?> onchange="this.form.submit()">
    Option 2
  </label>
</form>

If you do not need the server to know the selection, a lightweight client-only option is localStorage. Save on change and restore on load:

<script>
document.addEventListener('DOMContentLoaded', function () {
  var saved = localStorage.getItem('choice');
  if (saved) {
    var el = document.querySelector('input[name="choice"][value="' + saved + '"]');
    if (el) el.checked = true;
  }
  document.querySelectorAll('input[name="choice"]').forEach(function (rb) {
    rb.addEventListener('change', function () { localStorage.setItem('choice', this.value); });
  });
});
</script>

See MDN for radios (input type="radio") and Web Storage (localStorage), and PHP’s session handling (Sessions).

Recommended Answers

All 3 Replies

You will need to maintain the selection on the server side either by setting the selected radio button when you render it or via serverside generated javascript that sets the checked attribute, as you ha

ve above. The reason why the code you have doesn't work is because the currently rendered javascript refreshes along with the page (doesn't maintain the current execution thread) when you use location.href. So you will also want to send params on the url that are looked for via the php (not really certain the php code for getting url params as I'm most familiar with ASP and Perl) and then use that param to set the checked attribute on the radio buttons that you are re-rendering.

/* javascript */
function SelectRadio(rad){
var selected_radio = document.getElementById(rad).value; 
if(rad == 'rad2'){
window.location.href = 'radio_page.php';
document.getElementById(rad).checked = 'checked';

}
else{
window.location.href = 'radio_page.php?selected=rad2';
}

///////////radio_page///////
var selected= "the url value selected here";

if(selected == "rad2")
{

   echo "<input type=radio id=rad1  name=rad value=radio1 onclick=SelectRadio('rad1')> ";

  echo "<input type=radio checked=checked id=rad2 name = rad value=radio2 onclick=SelectRadio('rad2')> Time";
}else 
{
echo "<input type=radio checked=checked id=rad1  name=rad value=radio1 onclick=SelectRadio('rad1')> ";

  echo "<input type=radio id=rad2 name = rad value=radio2 onclick=SelectRadio('rad2')> Time";
}

An even better way would be to avoid the entire page refresh and use an Ajax call to only refresh the parts of the page that are actually being changed. What you would do is send a post/get back to the server and the server would render out the parts you need and then the callback function on the client side would swap out the parts the server sent. Here is a decent tutorial on basic ajax concepts

You will need to maintain the selection on the server side either by setting the selected radio button when you render it or via serverside generated javascript that sets the checked attribute, as you ha

ve above. The reason why the code you have doesn't work is because the currently rendered javascript refreshes along with the page (doesn't maintain the current execution thread) when you use location.href. So you will also want to send params on the url that are looked for via the php (not really certain the php code for getting url params as I'm most familiar with ASP and Perl) and then use that param to set the checked attribute on the radio buttons that you are re-rendering.

/* javascript */
function SelectRadio(rad){
var selected_radio = document.getElementById(rad).value; 
if(rad == 'rad2'){
window.location.href = 'radio_page.php';
document.getElementById(rad).checked = 'checked';

}
else{
window.location.href = 'radio_page.php?selected=rad2';
}

///////////radio_page///////
var selected= "the url value selected here";

if(selected == "rad2")
{

   echo "<input type=radio id=rad1  name=rad value=radio1 onclick=SelectRadio('rad1')> ";

  echo "<input type=radio checked=checked id=rad2 name = rad value=radio2 onclick=SelectRadio('rad2')> Time";
}else 
{
echo "<input type=radio checked=checked id=rad1  name=rad value=radio1 onclick=SelectRadio('rad1')> ";

  echo "<input type=radio id=rad2 name = rad value=radio2 onclick=SelectRadio('rad2')> Time";
}

An even better way would be to avoid the entire page refresh and use an Ajax call to only refresh the parts of the page that are actually being changed. What you would do is send a post/get back to the server and the server would render out the parts you need and then the callback function on the client side would swap out the parts the server sent. Here is a decent tutorial on basic ajax concepts

Thanks for your answer. I will try it and let you know :-)

I do not know how to thank you! I just tried it and it worked super fine :-)

Thanks a lot and Daniweb can mark this thread as solved :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.