1

I have a php variable $valuable='bottomValue'

and a select drop down inside a form which upon submit returns to the same page

<form action='' method='post'>
<select>
<option value='topValue'>One</option>
<option value='midValue'>Two</option>
<option value='bottomValue'>Three</option>
</select>
<input name='theSubmit' type='submit' />
</form>

Based upon the value of the $valuable how can I change the selected option to match.

For example on page load because the default value of the variable = 'bottomValue' option three would be selected

4 Answers 4

1

If you don't want to use other technology, javascript for example, you have to check the value for each option like this:

<option value='bottomValue' <?php echo ($valuable == 'bottomValue')?'selected':''; ?>>Three</option>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to do smth like this:

<form action='' method='post'>
<select>
<option value='topValue'>One</option>
<option value='midValue'>Two</option>
<option value='bottomValue' 
      <?php echo $valuable == 'bottomValue' ? 'selected' : '' ?>
      >Three</option>
</select>
<input name='theSubmit' type='submit' />
</form>

Comments

0

first make Array of your values and then do this

$values = array (
1 => 'topValue',
2 => 'middleValue',
3=> 'bottomValue',
);

and then

 <form action='' method='post'>
           <select>                                                         


    foreach( $values as $name => $v)
    {
      if( $name == $valuable )
           {
    echo '<option'.' value="'.$v.'"'.' selected="selected"'.'>'.$v.'</option>';
            }
    else
        {
    echo '<option'.' value="'.$v.'"'.'>'.$v.'</option>';
            }
         }

  </select>

best thing abt this Method You dun need inline php code for eacchhh option:)

Comments

0
$valueable = 'bottomValue';

// array of the options you want to display in your select dropdown
$options = array(
    'topValue' => 'One',
    'midValue' => 'Two',
    'bottomValue' => 'Three'
);

$html = '<form action='' method='post'>';
$html .= '<select>';
foreach($options as $value => $display){
    if($value == $valuable){
        $html .= '<option value="'.$value.'" selected>'.$display.'</option>';
    }else{
        $html .= '<option value="'.$value.'">'.$display.'</option>';
    }
}

$html .= '</select>';
$html .= '<input name="theSubmit" type="submit" />';
$html .= '</form>';

echo $html;

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.