首页 > 解决方案 > 通过另一个选择选项值过滤选择选项

问题描述

<select name="team">我的目标是使用 JS 函数进行过滤<select name="unit">。Team 与 Unit 是多对一的关系,因此过滤它会是更安全的选择。我在下面列出了表格和我的测试代码:


团队单位数据透视表

-------------------

Team --------- Unit

A ------------- 1

B ------------- 1

C ------------- 1

D ------------- 2

E ------------- 2

F ------------- 3

-------------------


<select name="unit" class="form-control" id="unit" onchange="refreshTeam()" required />
    <option value="" selected disabled>SELECT UNIT</option>
    @foreach ($units as $unit)
        <option value="{{$unit->id}}">{{ $unit->title }}</option>
    @endforeach
</select>


<select name="team" class="form-control" id="team" required />
    <option value="" selected disabled>SELECT TEAM</option>
    @foreach ($teams as $team)
        <option value="{{$team->id}}">{{ $team->title }}</option>
    @endforeach
 </select>


这是我对 refreshTeam() 的尝试,但我很确定这是错误的或需要改进

function refreshTeam() {
        var team = document.getElementById("team");
        var unit = document.getElementById("unit");

        <?php
            $unit = 'document.getElementById("unit").value';

            $team_unit = \DB::table('teams')
                            ->leftJoin('team_unit', 'teams.id', '=', 'team_unit.team_id')
                            ->leftJoin('units', 'units.id', '=', 'team_unit.unit_id')
                            ->select('teams.*')
                            ->where($unit, '=', 'team_unit.unit_id')
                            ->get();
            dd($team_unit);
        ?>
    }

标签: javascriptphplaravel

解决方案


refreshTeam 函数应该调用GET /unit/1/teams这将返回与单元 1 相关的所有团队。

  • 添加/unit/{unit}/teams路线
  • 在此路线中获取相关团队并将其作为 json 返回
  • 在您的 refreshTeam 中,使用 ajax 或 axios 调用具有相关单元的端点
  • 填充选择中的相关团队

推荐阅读