piyush
piyush

Reputation: 321

how to set selected value in html dropdown using php

I tried below code but it is not set the selected value :

<?php
   $form_field1 .= "<select name='typeofleave'> 
                   <option value='LWP'<?=$typeofleave == 'LWP' ? ' selected='selected'' : '';?> >LWP</option>
                    <option value='SL'<?=$typeofleave == 'SL' ? ' selected='selected'' : '';?> >SL</option>
                    <option value='PL'<?=$typeofleave == 'PL' ? ' selected='selected'' : '';?> >PL</option>
                </select>";
?>

Please help to solve it..

Upvotes: 3

Views: 10167

Answers (4)

cyrille
cyrille

Reputation: 2659

It should be a single selected keywork - not selected=xxx. And only one option should have it.

<?php
$form_field1 .= "<select name='typeofleave'>"
                . "<option value='LWP'" . ($typeofleave == 'LWP' ? ' selected' : '') . ">LWP</option>"
                . "<option value='SL'" . ($typeofleave == 'SL' ? ' selected' : '') . ">SL</option>"
                . "<option value='PL'" . ($typeofleave == 'PL' ? ' selected' : '') . " >PL</option>"
            . "</select>";
?>

Upvotes: 2

Chetan Ameta
Chetan Ameta

Reputation: 7896

Try below code.

$form_field1 = '';
$typeofleave = 'SL';

echo $form_field1 .= "<select name='typeofleave'>
                 <option value='LWP'".($typeofleave == 'LWP' ? ' selected' : '' )." >LWP</option>
                 <option value='SL'".($typeofleave == 'SL' ? ' selected' : '' ).">SL</option>
                 <option value='PL'".($typeofleave == 'PL' ? ' selected' : '' ).">PL</option>
            </select>";

Upvotes: 3

Pupil
Pupil

Reputation: 23978

Let me show you very neat method of doing this.

1) Take an array of options

2) Loop over it to get select <option>s.

3) Check if current is selected in loop.

Corrected code:

<?php
$form_field1 .= '<select name="typeofleave">';
$options = array();
$options['LWP'] = 'LWP';
$options['SL'] = 'SL';
$options['PL'] = 'PL';
if (! empty($options)) {
 foreach ($options as $option) {
  $selected = ($typeofleave == $option) ? 'selected="selected"' : '';
  $form_field1 .= '<option value="'.$option.'" ' . $selected . '>'.$option.'</option>';
 }
}
$form_field1 .= '</select>';
?>

Upvotes: 4

M. Eriksson
M. Eriksson

Reputation: 13645

Your quotes seems a bit off:

' selected='selected''

Should be

' selected="selected"'

Upvotes: 2

Related Questions