-1

I have a form that includes radio buttons in which results are stored in a database (Yes or No). I am trying to set the selected radio button from the stored database value but can't figure it out after following several recommended solutions. An echo of $existing_military_status returns 'No'. Because I'm using Wordpress, I must return the html from a function, hence why I'm using html .= nomenclature.

The result I'm getting is that the 'No' radio button is not checked. Note that I am not yet submitting the form, which will be done via an Ajax call.

How do I set the radio button to 'checked' after validating that it should be checked?

Any help is greatly appreciated.

Relevant PHP:

$existing_military_status = ( get_user_meta( $user_id, 'user-military-status', true ) ) ? get_user_meta( $user_id, 'user-military-status', true ) : '';

$html .= "<input id='yes' type='radio' name='user-military-status' value='Yes' if ($existing_military_status === 'Yes') echo 'checked=\"checked\"'>\n";
$html .= "<label for='yes'><span class='radio'>Yes</span></label>\n";
$html .= "</div>\n";
$html .= "<div id='military-no-container' style='float: left;' class='radio-container'>\n";
$html .= "<input id='no' type='radio' name='user-military-status' value='No' if ($existing_military_status === 'No') echo 'checked=\"checked\"'>\n";
$html .= "<label for='no'><span class='radio'>No</span></label>\n";
$html .= "</div>\n";
G Simmons
  • 35
  • 6

1 Answers1

1

The PHP interpreter isn't able to distinguish between the string and PHP code. I would suggest to create variables and conditional statements outside the strings.

$isYes = ($existing_military_status === 'Yes') ? 'checked' : '';
$isNo  = ($existing_military_status === 'No') ? 'checked' : '';

$html = "<input id='yes' type='radio' name='user-military-status' value='Yes' " . $isYes . ">\n";
$html .= "<input id='no' type='radio' name='user-military-status' value='No' " . $isNo . ">\n";
  • Could I enclose the PHP in tags so the interpreter can distinguish the PHP code? I actually tried it but couldn't get it to work. Just curious as it would streamline my code. I have quite a few radio buttons in the full form. – G Simmons Oct 04 '20 at 21:28
  • Yes you can enclose it. Please see the answer here https://stackoverflow.com/questions/13089747/if-statement-in-the-middle-of-concatenation – Muhammad Tashfeen Oct 04 '20 at 22:10
  • I failed to report back that this worked beautifully. Thank you! – G Simmons Dec 08 '20 at 20:40