Varun Kumar
Varun Kumar

Reputation: 478

Selecting dynamic default value in <SELECT>

I have a php script which updates user info. I have created an html form, which allows user to edit the values and enter new ones. Now when the form is loaded for the first time, it displays some default values taken from php variables. The works fine but the problem is with tag.

<input type = "text" name = "name" class = "text" value = "<?php echo $user->name; ?>" />

this works fine..

<select name = "department" value = "<?php echo $user->department; ?>">
    <option>Information Technology</option>
    <option>Computer Science</option>
    <option>Electronics & Communication</option>
    <option>Mechanical Engineering</option>
    <option>Civil Engineering</option>
    <option>Electrical & Electronics Engineering</option>
    <option>M.Tech</option>
    <option>MBA</option>
    <option>MCA</option>
</select>

how can I solve this issue?

Upvotes: 1

Views: 30316

Answers (3)

user3024707
user3024707

Reputation: 11

This can be solved with one single if statement.

For example:

<select name = "department">
<option value="IT">Information Technology</option>
<option value="CS">Computer Science</option>

<?php if (strlen($user->department)>1 ) 
echo "<option value="."$user->department"."selected='selected >"."$user->department"."</option>";?> 
</select>

Upvotes: 1

Alexander Wolff
Alexander Wolff

Reputation: 152

The Select tag doesn't have a value option. Use this instead:

For example:

<select name = "department">
<option value="IT" <?php if ($user->department == "IT") echo "selected='selected'";?> >Information Technology</option>
<option value="CS" <?php if ($user->department == "CS") echo "selected='selected'";?> >Computer Science</option>
</select>

Upvotes: 10

PiTheNumber
PiTheNumber

Reputation: 23542

Something like this would work

<select name = "department" value = "<?php echo $user->department; ?>">
    <option value="1" 
        <?= ( $user->department == 1 ? 'selected="selected"' : '' ) ?>>
        Information Technology
    </option>
    ...
</select>

Upvotes: 3

Related Questions