0

I have Table called predictions with columns Currorg1,Currorg2,Currorg3,Currorg4,Currorg5 now I am getting all these values in multi select dropdown. I want to implement dynamic dropdown i.e. when I select Currorg1 then all the values in Currorg2 must load values dependent on Currorg1 selection.

For e.g. this is my table | Curr0rg1 | Currorg2 | | -------- | ---------| | First | row1 | | Second | row2 | | First | row3 | | First | row4 | | Second | row 5 |

Now when First is selected it should display row1,row3,row4 in Currorg2 dropdown and so on. I have followed this tutorial: https://www.webslesson.info/2018/03/ajax-dynamic-dependent-dropdown-in-laravel.html but not sure what I am doing wrong.

Here is my controller:

 public function index(Request $request,ExportDataTable $dataTable)
    {
        if(request()->ajax())
        {
            if(!empty($request->BusinessUnit) || !empty($request->CurrOrg1)  || !empty($request->CurrOrg2)  || !empty($request->Role)  || !empty($request->Region)  || !empty($request->ProfessionalClassification)  || !empty($request->Gender)  || !empty($request->CurrOrg3)  || !empty($request->CurrOrg4)  || !empty($request->CurrOrg5) || !empty($request->L6) || !empty($request->L7) || !empty($request->Account))
            {             
                $loged_user =Auth::user();
                $user= DB:: table('users')
                    ->selectRaw('users.*, REPLACE(Org2, "Admin", "") AS ROrg2, REPLACE(Org1, "Admin", "") AS ROrg1, REPLACE(Org3, "Admin" , "") AS ROrg3')
                    ->where('email',$loged_user->email)
                    ->first();
                $query= DB:: table('predictions')
                        ->where('CurrOrg1','like','%'.$user->ROrg1.'%')
                        ->where('CurrOrg2','like','%'.$user->ROrg2.'%')
                        ->where('CurrOrg3','like','%'.$user->ROrg3.'%')
                        ->select('predictions.id','predictions.EmployeeNumber','predictions.Role','predictions.Region','predictions.CurrOrg1','predictions.CurrOrg2','predictions.RiskZone','predictions.Probablity','predictions.Rating','predictions.Feedback','predictions.Gender','predictions.CurrOrg3','predictions.CurrOrg4','predictions.CurrOrg5','predictions.ProfessionalClassification','predictions.Local_Expat','predictions.EmployeeRoleSeniority','predictions.FeedRisklevel','predictions.Feedinfluencers','predictions.Action','predictions.Fname','predictions.Lname','predictions.Avgweekhr','predictions.Account','predictions.L6','predictions.L7');
                        
                if(!empty($request->CurrOrg2)) {
                    $query->whereIn('CurrOrg2',$request->CurrOrg2);
                }

                if(!empty($request->Region)) {
                     $query->whereIn('Region',$request->Region);
                }

                if(!empty($request->ProfessionalClassification)) {
                     $query->whereIn('ProfessionalClassification',$request->ProfessionalClassification);
                }
                if(!empty($request->CurrOrg1)) {
                    $query->whereIn('CurrOrg1',$request->CurrOrg1);
                }
                if(!empty($request->CurrOrg3)) {
                     $query->whereIn('CurrOrg3',$request->CurrOrg3);
                }
                if(!empty($request->CurrOrg4)) {
                     $query->whereIn('CurrOrg4',$request->CurrOrg4);
                }
                if(!empty($request->CurrOrg5)) {
                     $query->whereIn('CurrOrg5',$request->CurrOrg5);
                }
                if(!empty($request->Role)) {
                    $query->whereIn('Role',$request->Role);
                }
                if(!empty($request->BusinessUnit)) {
                    $query->whereIn('BusinessUnit',$request->BusinessUnit);
                }
                if(!empty($request->Gender)) {
                     $query->whereIn('Gender',$request->Gender);
                }
                if(!empty($request->L6)) {
                     $query->whereIn('L6',$request->L6);
                }
                if(!empty($request->L7)) {
                     $query->whereIn('L7',$request->L7);
                }
                if(!empty($request->Account)) {
                     $query->whereIn('Account',$request->Account);
                }
                $data = $query->get(); 

            }  

            else
            {
                $loged_user =Auth::user();
                $user= DB:: table('users')
                    ->selectRaw('users.*, REPLACE(Org2, "Admin", "") AS ROrg2, REPLACE(Org1, "Admin", "") AS ROrg1, REPLACE(Org3, "Admin" , "") AS ROrg3')
                    ->where('email',$loged_user->email)
                    ->first();
                $data1 =DB:: table('predictions')
                        ->where('CurrOrg1','like','%'.$user->ROrg1.'%')
                        ->where('CurrOrg2','like','%'.$user->ROrg2.'%')
                        ->where('CurrOrg3','like','%'.$user->ROrg3.'%')
                        ->select('predictions.id','predictions.EmployeeNumber','predictions.Role','predictions.Region','predictions.CurrOrg1','predictions.CurrOrg2','predictions.RiskZone','predictions.Probablity','predictions.Rating','predictions.Feedback','predictions.Gender','predictions.CurrOrg3','predictions.CurrOrg4','predictions.CurrOrg5','predictions.ProfessionalClassification','predictions.Local_Expat','predictions.EmployeeRoleSeniority','predictions.FeedRisklevel','predictions.Feedinfluencers','predictions.Action','predictions.Fname','predictions.Lname','predictions.Avgweekhr','predictions.Account','predictions.L6','predictions.L7');
                       
                $data = $data1->get();   
                
                }
                
             
            return datatables()->of($data)
            ->addColumn('Feedback', function($data)
            {   
                if($data->Action == 'No' || is_null($data->Action))
                {
                return "<a href='#' style='background-color:#CA0088;color:#fff' class='btn btn-sm Feedback' id='".$data->id."'>Feedback</a>";
                }
                else
                   {
                     return "<a href='#' style='background-color:#00A300;color:#fff' class='btn btn-sm Feedback' id='".$data->id."'>Feedback</a>";
                   } 
            })
            ->escapeColumns([])
            ->make(true);

        }
        $Business_unit_name = DB::table('predictions')
                            ->select('BusinessUnit')
                            ->groupBy('BusinessUnit')
                            ->orderBy('BusinessUnit', 'ASC')
                            ->get();
        $CurrOrg1_name = DB::table('predictions')
                            ->select('CurrOrg1')
                            ->groupBy('CurrOrg1')
                            ->orderBy('CurrOrg1', 'ASC')
                            ->get();
        $CurrOrg2_name = DB::table('predictions')
                            ->select('CurrOrg2')
                            ->groupBy('CurrOrg2')
                            ->orderBy('CurrOrg2', 'ASC')
                            ->get();
        $CurrOrg3_name = DB::table('predictions')
                            ->select('CurrOrg3')
                            ->groupBy('CurrOrg3')
                            ->orderBy('CurrOrg3', 'ASC')
                            ->get();
        $CurrOrg4_name = DB::table('predictions')
                            ->select('CurrOrg4')
                            ->groupBy('CurrOrg4')
                            ->orderBy('CurrOrg4', 'ASC')
                            ->get();
        $CurrOrg5_name = DB::table('predictions')
                            ->select('CurrOrg5')
                            ->groupBy('CurrOrg5')
                            ->orderBy('CurrOrg5', 'ASC')
                            ->get();
        $Role_name = DB::table('predictions')
                            ->select('Role')
                            ->groupBy('Role')
                            ->orderBy('Role', 'ASC')
                            ->get();
        $Region_name = DB::table('predictions')
                            ->select('Region')
                            ->groupBy('Region')
                            ->orderBy('Region', 'ASC')
                            ->get();
        $Gender_name = DB::table('predictions')
                            ->select('Gender')
                            ->groupBy('Gender')
                            ->orderBy('Gender', 'ASC')
                            ->get();
        $ProfessionalClassification_name = DB::table('predictions')
                            ->select('ProfessionalClassification')
                            ->groupBy('ProfessionalClassification')
                            ->orderBy('ProfessionalClassification', 'ASC')
                            ->get();
        $Prediction= new Prediction;
        $Prediction_list= $Prediction::all();
        $Topcorrelators = DB::table('predictions')
                            ->select('Topcorrelators')
                            ->groupBy('Topcorrelators')
                            ->orderBy('Topcorrelators', 'ASC')
                            ->get();
               
        $L6_name = DB::table('predictions')
                  ->select('L6')
                  ->groupBy('L6')
                  ->orderBy('L6','ASC')
                  ->get();
        $L7_name = DB::table('predictions')
                  ->select('L7')
                  ->groupBy('L7')
                  ->orderBy('L7','ASC')
                  ->get();
        $Account_name = DB::table('predictions')
                  ->select('Account')
                  ->groupBy('Account')
                  ->orderBy('Account','ASC')
                  ->get();
            

        return view('admin.members.Predictions', compact('Business_unit_name','CurrOrg1_name','CurrOrg2_name','CurrOrg3_name','CurrOrg4_name','CurrOrg5_name','Role_name','Region_name','Gender_name','Topcorrelators','ProfessionalClassification_name','Prediction_list','L6_name','L7_name','Account_name'));


}
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
     function fetch(Request $request)
    {
     $select = $request->get('select');
     $value = $request->get('value');
     $dependent = $request->get('dependent');
     $data = DB::table('predictions')
       ->where($select, $value)
       ->groupBy($dependent)
       ->get();
     $output = '<option value="">Select '.ucfirst($dependent).'</option>';
     foreach($data as $row)
     {
      $output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
     }
     echo $output;
    }

This is my script:

 $('.dynamic').change(function(){
  if($(this).val() != '')
  {
   var select = $(this).attr("id");
   var value = $(this).val();
   var dependent = $(this).data('dependent');
   var _token = $('input[name="_token"]').val();
   $.ajax({
    url:"{{ route('dynamic_dependent') }}",
    method:"POST",
    data:{select:select, value:value, _token:_token, dependent:dependent},
    success:function(result)
    {
     $('#'+dependent).html(result);
    }

   })
  }
 });

 $('#CurrOrg1').change(function(){
  $('#CurrOrg2').val('');
  $('#CurrOrg3').val('');
 });

 $('#CurrOrg2').change(function(){
  $('#CurrOrg3').val('');
 });

This is my view:

        <div class="form-group" style="margin-right: 10px">
            

      <select name="CurrOrg1[]" id="CurrOrg1" multiple class="form-control input-lg dynamic" data-dependent="CurrOrg2">
     @foreach($CurrOrg1_name as $org1)
        <option value="{{ $org1->CurrOrg1 }}">{{ $org1->CurrOrg1 }}</option>
        @endforeach
    </select>       
    </div>
    <div class="form-group" style="margin-right: 10px">
      <select name="CurrOrg2[]" id="CurrOrg2" multiple class="form-control input-lg dynamic" data-dependent="CurrOrg3">
        <option value="">Select Org2</option>
      </select>       
  </div>
    <div class="form-group" style="margin-right: 10px">
      <select name="CurrOrg3[]" id="CurrOrg3" multiple class="form-control">
        
        <option value="">Select Org3</option>
       
      </select>       
  </div>
  {{ csrf_field() }}

Can someone suggest what I am doing wrong here?

prashant
  • 57
  • 1
  • 1
  • 15
  • `$('.dynamic').change(...` - I don't see any HTML elements with that class? What debugging have you tried? Do the selects render correctly on first load, is the HTML as expected? Any errors on the browser devtools console? What is the actual problem? – Don't Panic Oct 07 '21 at 08:41
  • It's $(#CurrOrg1).change(... in place of $('.dynamic').change(..., When I select CurrOrg1 value It should load all the values of CurrOrg2 with respect to CurrOrg1,currently it's loading all the values in CurrOrg2 it should display only where CurrOrg1 matches the selected Currorg1 – prashant Oct 07 '21 at 09:12
  • It is hard for anyone to help if the code in your question is not actually your code. Please edit your question, show us your **real** code, and the **real** problem. – Don't Panic Oct 07 '21 at 09:39
  • Code updated can you please check @Don'tPanic – prashant Oct 07 '21 at 11:21
  • I'll ask the same as last time: What debugging have you tried? Do the selects render correctly on first load, is the HTML as expected? Any errors on the browser devtools console? What is the actual problem? One observation: it seems risky to have 2 event handlers for the same element, one of which populates it and the other empties it. Theoretically the one that does AJAX should be slower, so the one that empties it should be done first, but this just seems like a bad approach. Why not empty it as the first part of the first handler? – Don't Panic Oct 08 '21 at 10:07
  • Yes data in currorg1 is loaded but when I select value from CurrOrg1 it does not load values in CurrOrg2 it returns blank similar for CurrOrg3 and CurrOrg4. – prashant Oct 08 '21 at 15:28
  • @Don't Panic Actually I am pretty new to development and Laravel.. working on it for first time..reached and developed this much from different forums and tutorials so not sure how exactly handlers ajax everything works in detail. I am using multiple dropdowns the tutorial I have followed is for single dropdown and I guess there is something to do with “id” how it will work not sure..stuck with this task weeks now..if you could help me resolve this would be really helpful – prashant Oct 08 '21 at 15:33
  • Select renders value in Currorg1 on first load..when I select something from Currorg1 it should load all the values in currorg2 dropdown where Currorg1=selected Currorg1 – prashant Oct 08 '21 at 15:37
  • What debugging have you tried? In your browser devtools, can you see the AJAX POST happening, correctly, and are the expected values being sent? How about the response, is your PHP returning the right data, in the right format? I've already pointed out that I think having 2 `.change()` handlers is a bad approach, and why, have you checked if that is a problem? There are many examples of doing this here on SO, have you checked them? Eg https://stackoverflow.com/q/34409769, https://stackoverflow.com/q/10570904, https://stackoverflow.com/q/8749326, https://stackoverflow.com/q/46758066 ... – Don't Panic Oct 09 '21 at 10:11
  • @Don'tPanic I checked after inspect element in Network tab the values of Org2 are getting when I select Org1...but can't see values in dropdown and the when i select 2 values from Org1 only dependent value of first value is getting fetched – prashant Oct 19 '21 at 07:23

0 Answers0