I am using below code to keep the radio button selection after a form submission, but it keep resetting to the last button after form submission
<input type="radio" name="button" value="Yes" <?php if(isset($_POST['button']) == 'Yes') echo ' checked="checked"';?> />Yes
<input type="radio" name="button" value="No" <?php if(isset($_POST['button']) == 'No') echo ' checked="checked"';?> />No
How can I keep the selection ?
Give people control and align with their expectations (Good): It is better to have a selected radio button by default, given that people cannot deselect and set the button back to its original state once one has been selected. A default selection sets the correct user expectation.
To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected.
There should not be an input element without a form element. You are not going to get the HTML to respond the way you want it to if you do not use it correctly. Multiple submit buttons would indicate the need for multiple forms.
isset()
returns a boolean
. As such, comparing directly to Yes
/No
is not what you want.
What you want is:
if (isset($_POST['button']) && $_POST['button'] == 'Yes')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With