duandaiqin6080 2019-04-09 11:32
浏览 91

如何从下拉列表中获取所选值的ID并将其用于laravel中的其他下拉列表?

I'm newbie at Laravel and on stackoverflow. I'm making an app for registration. I want to show all those ids of section where class_id is selected in upper dropdown.

 $cid=DB::table('classses')->get();
 $counterr=0;

  $sec=DB::table('sections')->where('class_id',$cid)->get();
  $counterrr=0;

Dropdown menu for Class

   <div class="col-md-6">
   <select class="" name="class_id">
         <option value="null">Class</option>
         @foreach($cid as $cc)
             @if($counterr==0)
                <option selected="selected" value="{{$cc->id}}">{{$cc->title}}</option>
                {$counterr++}}
             @else
                 <option value="{{$cc->id}}">{{$cc->title}}</option>
             @endif
        @endforeach
    </select>

Dropdown menu for Section where I want to get all the values of section where class_id is upper selected

       <select section="" name="section_id">
           <option value="null">Section</option>
           @foreach($sec as $sc)
               @if($counterrr==0)
                   <option selected="selected" value="{{$sc->id}}">{{$sc->title}}</option>
                   {{$counterrr++}}
               @else
                   <option value="{{$sc->id}}">{{$sc->title}}</option>
               @endif
            @endforeach
    </select>

Please help me in these case. You can freely ask anything if you want to.

  • 写回答

1条回答 默认 最新

  • douzhe9927 2019-04-09 11:45
    关注

    You do not need to set a $counter in order to set the first select option to selected. Instead, you can check if the $key == 0:

    <select class="" name="class_id">
        <option value="null">Class</option>
        @foreach($cid as $key => $cc)
            <option {{ $key == 0 ? 'selected="selected"' : '' }} value="{{$cc->id}}">{{$cc->title}}</option>
        @endforeach
    </select>
    

    Here we use a ternary expression to echo out the selected option based on if $key equals 0. If not, it will not echo out anything.

    评论

报告相同问题?