mardi 9 octobre 2018

Multiselect dropdown is working as single select in laravel? How to populate dependent dropdown based on multiple select?

I have two multi-select drop-down lists. I want to populate the 2nd multi-select dropdown based on the 1st multi-select drop-down.

web.php

Route::get('allstate/{id}', 'LocationController@allstate');

Country dropdown (1st)

<select  multiple="multiple" name="country[]" id="country" class="select">                 
@foreach($country_data as $country)
     <option value="" >
          </option>
@endforeach
</select>

State dropdown (2nd)

<select  multiple="multiple" name="city[]" id="city" class="select">                   

 </select>

Controller

public function index()
{
 $country_data=DB::table('country')->select('country_id','country_name')->orderby('country_name')->get();
return view('location',compact('country_data') );
}
public function allstate($id)
{
$state_data= DB::table('state')->whereIn('country_id',$id)->select('state_id','state_name')->get();
return json_encode($caste_data);
}

Script

<script type="text/javascript">
$(document).ready(function() {
$('select[name="country[]"]').on('change', function() {
    var countryID = $(this).val();

    if(countryID) {
        $.ajax({
            url: 'allstate/'+countryID,
            type: "GET",
            dataType: "json",
            success:function(data) {
                $('select[name="city[]"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="city[]"]').append('<option value="'+ value.city_id +'">'+ value.city_name +'</option>');
                });

            }
        });
    }else{
        $('select[name="city[]"]').empty();
    }
});
});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire