Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep radio button selected after a form submit

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 ?

like image 456
acr Avatar asked Aug 26 '13 18:08

acr


People also ask

Should radio button be selected by default?

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.

How can I get radio button to click?

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.

Do radio buttons need to be in a form?

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.


1 Answers

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')
like image 92
Jason McCreary Avatar answered Sep 26 '22 13:09

Jason McCreary