我使用codeigniter为客户创建下拉列表。
如果我输入选中,则自动选择下拉列表中的最后一个客户。
是否可以选择该foreach内的客户?
我的代码段:
<?php foreach ($customers as $c): ?>
<option value="<?php echo $c->customer_id;?>"><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
答案 0 :(得分:1)
只需在<option>
里面添加三元条件for循环,其中$selectedOption
是您要选择的值。
<?php $selectedOption = "yourvalue";
foreach ($customers as $c): ?>
<option value="<?php echo $c->customer_id;?>" <?= ($c->customer_id == $selectedOption ? "selected" : "")><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
答案 1 :(得分:1)
是的。但是,您必须知道当前选择了哪个客户,然后在循环内部检查所选择的customer_id是否与当前客户相同:
<?php
$chosenCustomer_id = 5; //of course don't hardcode it
foreach ($customers as $c):
$selected = $c->customer_id == $chosenCustomer_id ? 'selected' : '';
?>
<option value="<?php echo $c->customer_id;?>" <?php echo $selected; ?>> <?php echo ><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>
答案 2 :(得分:0)
在选项标签中使用所选属性
选择的需要根据条件
$selected=(condition): "selected","";
<option <?php echo $selected; ?>> Option Inner Html </option>
答案 3 :(得分:0)
将变量与选项标签
中的属性进行比较 <?php $chosenCustomer_id = 5;?>
<select name="customer" required>
<?php foreach ($customers as $c){?>
<option <?=($chosenCustomer_id==$c['customer_id']?'selected="selected"':'')?> value="<?=$c['customer_id']?>"><?=$c['customer_name']?></option>
<?php }
?>
</select>