首页 > 解决方案 > laravel 刀片选择选项被全部选中

问题描述

我试图将option一个select元素标记为已选,但它们都被选中了。

刀片 HTML

<h1>value = {{ $entity->field ?? 'this is new' }}</h1>
<select name="field">
    <option value="option_a" @if ($entity->field ?? '' == 'option_a') selected="selected" @endif>Option A</option>
    <option value="option_b" @if ($entity->field ?? '' == 'option_b') selected="selected" @endif>Option B</option>
    <option value="option_c" @if ($entity->field ?? '' == 'option_c') selected="selected" @endif>Option C</option>
</select>

如果我正在创建一个新记录,那么这是新的打印在h1.

如果我正在编辑现有记录,则存储在 db 中的选项会打印在h1(比如说 option_b)中。

那么为什么所有选项都获得selected属性呢?

HTML 输出

<h1>value = option_b</h1>
<select name="field">
    <option value="option_a" selected="selected">Option A</option>
    <option value="option_b" selected="selected">Option B</option>
    <option value="option_c" selected="selected">Option C</option>
</select>

标签: laravellaravel-blade

解决方案


看起来你有一个逻辑问题。看起来您要创建一个三元组,然后决定进行标准的 if-check,但可能会在代码中留下一些三元组的逻辑。

这部分:

 @if ($entity->field ?? '' == 'option_a') selected="selected" @endif

似乎缺少 , 的另一面??:因此总是会评估为true

相反,请尝试:

@if ($entity->field == 'option_a') selected @endif

推荐阅读