0

I have a form on which I POST the data with PHP. When the data is send I want to show the new values. Doing this on textfields is easy, but how can I set the new values on the radioboxes. My default value is Male here.

PHP

if (isset($_POST['Submit'])) {
    update_user($_POST['name'], $_POST['sex']); // the update method
}

HTML

<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <label for="name">Name:</label>
  <input type="text" name="name" size="30" value="<?php echo (isset($_POST['name'])) ? $_POST['name'] : ""; ?>">
  <br /><br />
  <label for="sex">Sex:</label>
  <input type="radio" checked="checked" name="sex" value="<?php echo (isset($_POST['sex'])) ? $_POST['sex'] : "M"; ?>" /> Male
  <input type="radio" name="sex" value="<?php echo (isset($_POST['sex'])) ? $_POST['sex'] : "F"; ?>" /> Female
</form>
1
  • You have to add checked = "checked" if value is selected. Check the answers for details. Commented Mar 11, 2010 at 13:55

4 Answers 4

2
<input type="radio" <?php if ($_POST['sex'] == "M") print "checked=\"checked\"";?> name="sex" value="M" /> Male
<input type="radio" <?php if ($_POST['sex'] == "F") print "checked=\"checked\"";?> name="sex" value="F" /> Female
Sign up to request clarification or add additional context in comments.

Comments

1

Well you know the values of the Sex radioboxes...M and F. You want to see which one needs to be checked. This will default the checked to be Male like you currently have it.

<input type="radio" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> name="sex" value="M" /> Male
<input type="radio" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> name="sex" value="F" /> Female

1 Comment

Actually Aarons example is exactly what I wanted, with default "M" checked. Typo though for the statement () ? :, not ;
0

Try the following instead:

<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
  <label for="name">Name:</label> 
  <input type="text" name="name" size="30" value="<?php echo (isset($_POST['name'])) ? $_POST['name'] : ""; ?>"> 
  <br /><br /> 
  <label for="email">Sex:</label> 
  <input type="radio" name="sex"<?php echo (@$_POST['sex'] == "M") ? 'checked="checked"' : "";?> value="M" /> Male 
  <input type="radio" name="sex" <?php echo (@$_POST['sex'] == "F") ? 'checked="checked"' : "";?> value="F" /> Female 
</form> 

Using the @ character means you don't need to use isset, it will suppress the warnings/errors if the variable isn't in the $_POST array.

Comments

-2

Try with print_r( $_POST );exit; to see the values sending in the variable POST.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.