Kyle
Kyle

Reputation: 115

Filter select-options through another select-option value

My target is to filter <select name="team"> by using a JS function from <select name="unit">. Team is a many-to-one relationship with Unit so filtering it would be much more safer option. I've list down the tables and my test codes below:


Team-Unit pivot table

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

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>


Here's my try on refreshTeam(), but I'm pretty sure this is wrong or needs improvement

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);
        ?>
    }

Upvotes: 0

Views: 59

Answers (1)

Thijs
Thijs

Reputation: 1012

The refreshTeam function should call GET /unit/1/teams this will return all teams related to unit 1.

  • Add the /unit/{unit}/teams route
  • In this route fetch the related teams and return it as json
  • In your refreshTeam use ajax or axios to call the endpoint with the related unit
  • Populate the related teams in the select

Upvotes: 0

Related Questions