I have a dropdown list that works fine, but halfway through the list of 80 values is the one I want as selected by default
$cosOptions = cos_options();
Is the variable
<td><select name="options"><?php print $cosOptions; ?></select></td>
Prints the dropdown, then the function below.
function cos_options()
{
$dbh = dbh_get();
$options = '';
$sql = 'select code, descr FROM cos';
$stmt = $dbh->prepare($sql);
$stmt->execute();
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) break;
$options .= '<option value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
}
dbh_free($dbh);
return $options;
}
The Postgres table only has two columns and 80 rows
code descr
D1 Pizza
D2 Bread
D3 Cornflakes etc,.
What I need is D43 Rice to be selected at first because 90% of the time it will be this. How can I achieve this? I've gone through a bunch of posts on here but can't get it working.
you can use this code which select D43Rice option value select. do not use D43 Rice and merge D43Rice , sometime text space will add
<?php
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) {
break;
}
$selected = '';
if ($r['code'].$r['descr'] == 'D43Rice') {
$selected = 'selected="selected"';
}
$options .= '<option "' . $selected . '" value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
}
?>
this is update condition which check code value
<?php
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) {
break;
}
$selected = $r['code'].$r['descr'] = 'D43Rice' ? 'selected="selected"' : '';
$options .= '<option "' . $selected . '" value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
}
?>
function cos_options()
{
$dbh = dbh_get();
$options = '';
$sql = 'select code, descr FROM cos';
$stmt = $dbh->prepare($sql);
$stmt->execute();
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) break;
$temp=$r['code']. ' '. $r['descr'];
if($temp=="D43 Rice") //check for whatever you want to set selected
{
$options .= '<option selected value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
}
else
{
$options .= '<option value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
}
}
dbh_free($dbh);
return $options;
}
<?php
if ($whateveryourneededcodeis == "D43")
{
$selected = 'selected="selected"';
} else {
$selected = '';
}
$options .= '<option value="'.$r['code'].''.$r['descr'].'" $selected>'
.$r['code'].''.$r['descr'].'
</option>';
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.