【问题标题】:laravel blade select options are getting all selectedlaravel 刀片选择选项被全部选中
【发布时间】:2020-09-16 08:46:56
【问题描述】:

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

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>

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

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

    这部分:

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

    似乎缺少?? 的另一边:,因此将始终评估为true

    请尝试:

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

    【讨论】:

    • ?? '' 部分,如果我在创建记录时没有设置$entitiy
    • 好的,但仍然是同样的问题。试试@if(isset($entity) &amp;&amp; $entity-&gt;field == 'option_a')
    【解决方案2】:

    选择的语法是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 2015-07-03
      • 2018-11-21
      • 2021-10-23
      相关资源
      最近更新 更多