1

I have a drop down form item with four options.

<p>Priority: 
  <select required name=\"priority\">
    <option default value=\"1\">1 - 10 days</option>
    <option value=\"2\">2 - 5 days</option>
    <option value=\"3\">3 - 48 hours</option>
    <option value=\"4\">4 - 24 hours</option>
  </select>
</p>

http://jsfiddle.net/2nmxN/

These values are already stored in the SQL database with either 1,2,3,4. The page I am working on is an edit page of sorts, so I would like to have whichever value is set in the database be selected on the drop down, so the user does not have to reselect the value upon submission. How can I get it to find the value and select the correct option depending what is set? I have no problem doing this with a text field like this:

echo "<p>Cost: <input required type=\"text\" name=\"cost\" value=\"".$cost."\">";

Do I have to do four different if statements for each value (if ($priority == 1) {...}) etc.?

2
  • 1
    ya you have to do that way Commented Jun 5, 2013 at 13:07
  • 1
    You could also store the values in an array - use the value as the key, and the text description as the value; and iterate through that. You'll still need to check each time, but it might be less typing, and it's easier to maintain. Commented Jun 5, 2013 at 13:08

3 Answers 3

5

If the options were stored in an associative array, you could write something like:

foreach ($options as $value => $label) {
    echo '<option value="', $value, '"', ($dbValue == $value ? ' selected="selected"' : ''), '>', $label, '</option>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

You do not have to do four different if statements for each value. You have to do four if statements, one for each value.

1 Comment

I meant the latter, didn't mean to word it that way. Thank you.
0
foreach ($options as $value => $label) 
{
  if(isset($_POST['priority']) && $_POST['priority']==$value)
  {
    $selected = 'selected="selected"';
  }
  else
  {
    $selected='';
  }

  echo '<option value="'. $value. '" '.$selected.'>'. $label. '</option>';
}

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.