Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set selected value in html dropdown using php

Tags:

html

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..

like image 375
piyush Avatar asked Feb 09 '26 17:02

piyush


1 Answers

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>';
?>
like image 126
Pupil Avatar answered Feb 12 '26 15:02

Pupil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!