oziel
124
5
General

Select field autoload LGAs from State

Posted 1 month ago by oziel

The LGA field is not auto loading after state selection fields.blade.php

<!-- State Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('state_id', 'State Id:') !!}
    {!! Form::select('state_id',[''=>'--- Select Country ---']+$states,null,['class'=>'form-control']) !!}
     
</div>

<!-- Lga Field -->
<div class="form-group col-sm-6">
    {!! Form::label('lga', 'Lga:') !!}
    {!! Form::select('lga_id',[''=>'--- Select LGA ---'],null,['class'=>'form-control']) !!}
</div>

postController.php

public function create()
    {
        
        $states = DB::table('states')->pluck("name","state_id")->all();
        return view('posts.create', compact('states'));
    }

        /**
     * Show the application selectAjax.
     *
     * @return \Illuminate\Http\Response
     */

    public function selectAjax(Request $request)

    {

        if($request->ajax()){

            $states = DB::table('lgas')->where('state_id',$request->state_id)->pluck("name","lga_id")->all();

            $data = view('posts.ajax-select',compact('lgas'))->render();

            return response()->json(['options'=>$data]);

        }

    }

ajax-select.blade.php

<option>--- Select LGA ---</option>

@if(!empty($lgas))

  @foreach($lgas as $key => $value)

    <option value="{{ $key }}">{{ $value }}</option>

  @endforeach

@endif

route

Route::post('ajax-select', ['as'=>'ajax-select','uses'=>'[email protected]']);

app.blade.php

<!-- this is dropdown for states and lgas -->
<script type="text/javascript">

  $("select[name='state_id']").change(function(){

      var state_id = $(this).val();

      var token = $("input[name='_token']").val();

      $.ajax({

          url: "<?php echo route('ajax-select') ?>",

          method: 'POST',

          data: {state_id:state_id, _token:token},

          success: function(data) {

            $("select[name='lga_id'").html('');

            $("select[name='lga_id'").html(data.options);

          }

      });

  });

</script>

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.