laravel blade select 选项全部 selected

laravel blade select options are getting all selected

我正在尝试将 select 元素的 option 标记为已选中,但它们都被选中了。

BLADE 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 中。

如果我正在编辑现有记录,那么存储在数据库中的选项将打印在 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>

选择的语法是这样的:

<option value="audi" selected>Audi</option>

所以尝试:

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

看来你的逻辑有问题。看起来你正要制作一个三元,然后决定使用标准 if-check,但可能在代码中留下了三元的一些逻辑。

这部分:

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

似乎缺少 ?? 的另一侧,即 :,因此将始终计算为 true

相反,尝试:

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