Benjamin W
Benjamin W

Reputation: 2848

php select-option post back retain value

I have a form with input type-select however when page submit and post back with error message The select value is clean, I try to use radio button (checked unchecked) to retain the value, yet it is not working.

//HTML///////////////////////////////////////////////////////////////////
<select name="age">
     <option value="">Age</option>
     <option value="14-17" <?PHP echo $age_14; ?>>14 - 17</option>
     <option value="18-29" <?PHP echo $age_18; ?>>18 - 29</option>
</select>

//PHP////////////////////////////////////////////////////////////////////
$age_14="unchecked";
$age_18="unchecked";

$age=$_POST['age'];
  if($age=='14-17'){$age_14="checked";}
  else if($age=='18-29'){$age_18="checked";}

Upvotes: 0

Views: 2744

Answers (3)

jaco
jaco

Reputation: 3516

With select tag you have to use selected="selected" not checked.

Try with:

$age_14 = "";
$age_18 = "";

$age = $_POST['age'];
if ($age == '14-17') {
    $age_14 = 'selected="selected"';
} elseif ($age == '18-29') { 
    $age_18 = 'selected="selected"';
}

Upvotes: 1

user1726343
user1726343

Reputation:

There is no checked attribute. You need to use selected:

$age=$_POST['age'];
$age_14 = $age=='14-17'?"selected":"";
$age_18 = $age=='18-29'?"selected":"";

Upvotes: 1

Colin M
Colin M

Reputation: 13348

With select boxes, the attribute is selected, not checked. You also do not need the unchecked attribute.

Upvotes: 1

Related Questions