0

my goal is get current value from database, selected in the dropdown list. I tried that code but it shows always "Ndone" in the dropdownlist

<select name="work" id="work" value="<?php echo $work; ?>">
     <option selected="selected" value=""></option>
     <option selected="selected" value="DONE">DONE</option>
     <option selected="selected" value="NDONE">NDONE</option>
</select>

Also this one and nothing just the first row that selected in the dropdownlist

<select name="work" id="work" value="<?php echo $work; ?>">
     <option value=""></option>
     <option value="DONE">DONE</option>
     <option value="NDONE">NDONE</option>
</select>

I don't know what to do, any help please

When i use a textfield it works, so there's no problem with the variable $work

<input type="text" name="work" value="<?php echo $work; ?>"/>
13
  • Problem may be in your SQL, which isn't in your question, even some more PHP. Just dropdown code isn't enough to know for sure. Commented Oct 23, 2014 at 14:51
  • php works correctly because when i use a text field instead of dropdownlist, it shows the current value from database, no problem with that Commented Oct 23, 2014 at 14:56
  • Then see what the differences are between both and base yourself on that. Commented Oct 23, 2014 at 14:57
  • Why are all 3 options selected="selected"? Commented Oct 23, 2014 at 14:59
  • is $work what is set to either 'DONE or "NDONE"? Commented Oct 23, 2014 at 15:01

2 Answers 2

1

<select> does not have a "value" Attribute. You must add the selected attribute to one option.

<?php
$options = array(
    '',
    'DONE',
    'NDONE',
);
?>

<select name="work" id="work">
    <?php foreach ($options as $option): ?>
        <option value="<?php echo $option ?>"<?php echo $option === $work ? ' selected="selected"' : '' ?>><?php echo $option ?></option>
    <?php endforeach ?>
</select>
Sign up to request clarification or add additional context in comments.

Comments

0

As per your example you could do this:

You just need to check each option value against the $work variable and if it matches add the selected attribute.

<select name="work" id="work">
     <option value=""></option>
     <option value="DONE" <?php echo($work == 'DONE'?'selected="selected"':''); ?>>DONE</option>
     <option value="NDONE" <?php echo($work == 'NDONE'?'selected="selected"':''); ?>>NDONE</option>
</select>

2 Comments

that doesn't work, it shows nothing, Thank you anyway :)
Sorry I had an error - see update - The second ? in the ternary operator should have been a :

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.